C 库 - iswspace() 函数

❮ C 标准库 - <wctype.h>


C wctype 库中的 iswspace() 函数用于检查给定的宽字符(类型为 wint_t)是否为空白字符。

空白字符包括空格、制表符、换行符以及其他在各种语言环境中被视为空白的字符。具体来说,这些字符包括:

  • 空格 (0x20)
  • 换页符 (0x0c)
  • 换行符 (0x0a)
  • 回车符 (0x0d)
  • 水平制表符 (0x09)
  • 垂直制表符 (0x0b)

语法

以下是iswspace() 函数的 C 库语法 -

int iswspace( wint_t ch )

参数

此函数接受一个参数 -

  • ch - 需要检查的是"wint_t"类型的宽字符。

返回值

如果宽字符是空格字符,则此函数返回非零值,否则返回零。

示例 1

以下是演示 iswspace() 函数用法的基本 C 示例。

#include <stdio.h>
#include <wchar.h>
#include <wctype.h>

int main(void) {
   wchar_t ch = L' ';
   
   // 使用三元运算符
   int is_whitespace = iswspace(ch) ? 1 : 0; 

   printf("Character '%lc' is%s whitespace character
", ch, is_whitespace ? "" : " not");

   return 0;
}

输出

以下是输出 -

Character ' ' is whitespace character

示例 2

让我们创建另一个 C 程序,并使用 iswspace() 来验证数组中的每个元素是否为空格。

#include <locale.h>
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>

int main(void) {
    // 将语言环境设置为 "en_US.utf8"
    setlocale(LC_ALL, "en_US.utf8");
    
    // 宽字符数组
    wchar_t wchar[] = {
        L'X', L' ', L'
', L'	', L'@', L'\u00A0', L'\u2003'
    };
    size_t size = sizeof(wchar) / sizeof(wchar[0]);

    printf("Checking whitespace characters:
");
    for (size_t i = 0; i < size; ++i) {
        wchar_t ch = wchar[i];
        printf("Character '%lc' (U+%04X) is %s whitespace character
", ch, ch, iswspace(ch) ? "a" : "not a");
    }
    return 0;
}

输出

以下是输出 -

Checking whitespace characters:
Character 'X' (U+0058) is not a whitespace character
Character ' ' (U+0020) is a whitespace character
Character '
' (U+000A) is a whitespace character
Character ' ' (U+0009) is a whitespace character
Character '@' (U+0040) is not a whitespace character
Character ' ' (U+00A0) is not a whitespace character
Character ' ' (U+2003) is a whitespace character

示例 3

以下 C 语言示例使用 iswspace() 函数在遇到空格后中断语句。

#include <stdio.h>
#include <wchar.h>
#include <wctype.h>

int main(void) {
    // 宽字符数组
    wchar_t statement[] = L"Tutrialspoint India pvt ltd";
    // 计算宽字符的长度
    size_t len = wcslen(statement);

   for (size_t i = 0; i < len; ++i) {
      // 检查当前字符是否为空格
      if (iswspace(statement[i])) {
         // 如果发现空格,则打印换行符
         putchar('
');
      } else {
         // 如果当前字符不是空格,则打印当前字符
         putchar(statement[i]);
      }
   }
   return 0;
}

输出

以下是输出 -

Tutrialspoint
India
pvt
ltd

❮ C 标准库 - <wctype.h>