Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน iswblank() ใน C++ STL

ภาพรวม

iswblank() เป็นฟังก์ชันใน C++ STL (header <cwctype> หรือ <ctype.h>) ใช้ตรวจสอบว่า Wide Character เป็น Blank Character หรือไม่

Blank Character คืออะไร?

Blank characters คือตัวอักษรที่ใช้เว้นวรรค แต่อาจไม่ใช่ Whitespace ทั้งหมด โดยมาตรฐาน C++ กำหนดให้เป็น:

  • ' ' (Space, 0x20)
  • \t (Horizontal Tab, 0x09)
  • อาจรวม wide-space characters ใน locale อื่นๆ

หมายเหตุ: \n, \r, \v, \f เป็น Whitespace แต่ ไม่ใช่ Blank

Syntax

int iswblank(wint_t ch);

ค่าที่คืน

  • Non-zero (true) - ถ้า ch เป็น Blank character
  • 0 (false) - ถ้าไม่ใช่

ตัวอย่างที่ 1: นับจำนวน Blank Characters

#include <cwctype>
#include <iostream>
#include <clocale>
using namespace std;

int main() {
    setlocale(LC_ALL, "en_US.UTF-8");
    wchar_t str[] = L"\u0757\u077c\u0020\u00c5\u00d5\u00dd\u0009\u00a5";
    int count = 0;

    for (int i = 0; i < wcslen(str); i++) {
        if (iswblank(str[i]))
            count++;
    }
    wcout << L"Number of blank characters in \"" << str << L"\" = " << count;
    return 0;
}

ผลลัพธ์

Number of blank characters in "ݼݗ ÅÕÝ	¥" = 2

(มี Space 0x20 และ Tab 0x09 รวม 2 ตัว)

ตัวอย่างที่ 2: ตรวจสอบตัวอักษรเดี่ยว

#include <cwctype>
#include <iostream>
using namespace std;

int main() {
    wchar_t chars[] = {L' ', L'\t', L'\n', L'a', L'1'};
    for (wchar_t c : chars) {
        wcout << L"'" << c << L"' is blank: " << iswblank(c) << endl;
    }
    return 0;
}

ผลลัพธ์

' ' is blank: 1
'	' is blank: 1
'
' is blank: 0
'a' is blank: 0
'1' is blank: 0

คำอธิบายเพิ่มเติม

  • ต้องใช้ setlocale() เพื่อรองรับ Locale/Unicode อย่างถูกต้อง
  • สำหรับ ASCII ใช้ isblank() (header <cctype>)
  • ใช้กันในการ Tokenizing, Parsing ข้อความ
  • Wide version รองรับ Unicode Space characters (เช่น Ideographic Space U+3000)

เปรียบเทียบ iswblank vs iswspace

Characteriswblankiswspace
Space ( )✓✓
Tab (\t)✓✓
Newline (\n)✗✓
Carriage Return (\r)✗✓
Vertical Tab (\v)✗✓
Form Feed (\f)✗✓