C库 - iswspace() 函数



C 的wctypeiswspace() 函数用于检查给定的宽字符(类型为 wint_t)是否为空格字符。

空格字符包括空格、制表符、换行符以及在各种区域设置中被认为是空格的其他字符。具体来说,这些字符是:

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

语法

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

int iswspace( wint_t ch )

参数

此函数接受一个参数:

  • ch − 要检查的类型为 'wint_t' 的宽字符。

返回值

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

示例 1

以下是一个基本的 C 示例,演示了 iswspace() 函数的使用。

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

int main(void) {
   wchar_t ch = L' ';
   
   // use ternary operator 
   int is_whitespace = iswspace(ch) ? 1 : 0; 

   printf("Character '%lc' is%s whitespace character\n", 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) {
    // Set the locale to "en_US.utf8"
    setlocale(LC_ALL, "en_US.utf8");

    // Array of wide characters 
    wchar_t wchar[] = {
        L'X', L' ', L'\n', L'\t', L'@', L'\u00A0', L'\u2003'
    };
    size_t size = sizeof(wchar) / sizeof(wchar[0]);

    printf("Checking whitespace characters:\n");
    for (size_t i = 0; i < size; ++i) {
        wchar_t ch = wchar[i];
        printf("Character '%lc' (U+%04X) is %s whitespace character\n", 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) {
   // wide char array
   wchar_t statement[] = L"Tutrialspoint India pvt ltd";
   // find the length of wide char
   size_t len = wcslen(statement);

   for (size_t i = 0; i < len; ++i) {
      // Check if the current character is whitespace
      if (iswspace(statement[i])) {
         // Print a newline character if whitespace is found
         putchar('\n');
      } else {
         // Print the current character if it's not whitespace
         putchar(statement[i]);
      }
   }
   return 0;
}

输出

以下是输出:

Tutrialspoint
India
pvt
ltd
c_library_wctype_h.htm
广告
© . All rights reserved.