用C語言判斷字符是否為空白字符或特殊字符的方法
C語言isspace()函數:判斷字符是否為空白字符
頭文件:
#include <ctype.h>
定義函數:
int isspace(int c);
函數說明:檢查參數c是否為空格字符,也就是判斷是否為空格(' ')、定位字符(' \t ')、CR(' \r ')、換行(' \n ')、垂直定位字符(' \v ')或翻頁(' \f ')的情況。
返回值:若參數c 為空白字符,則返回非 0,否則返回 0。
附加說明:此為宏定義,非真正函數。
范例:將字符串str[]中內含的空格字符找出,并顯示空格字符的ASCII 碼。
#include <ctype.h> main(){ char str[] = "123c @# FD\tsP[e?\n"; int i; for(i = 0; str[i] != 0; i++) if(isspace(str[i])) printf("str[%d] is a white-space character:%d\n", i, str[i]); }
執(zhí)行結果:
str[4] is a white-space character:32 str[7] is a white-space character:32 str[10] is a white-space character:9 // \t str[16] is a white-space character:10 // \t
C語言ispunct()函數:判斷字符是否為標點符號或特殊字符
頭文件:
#inlude <ctype.h>
ispunct() 函數用來檢測一個字符是否為標點符號或特殊字符,其原型為:
int ispunct(int c);
【參數】c 為需要檢測的字符。
【返回值】若 c 為標點符號或特殊符號(非空格、非數字和非英文字母)返回非 0 值,否則返回 0。
注意,此為宏定義,非真正函數。
【實例】列出字符串str 中的標點符號或特殊符號。
#include <stdio.h> #include <ctype.h> int main () { int i=0; int cx=0; char str[]="Hello, welcome!"; while (str[i]) { if (ispunct(str[i])) cx++; i++; } printf ("Sentence contains %d punctuation characters.\n", cx); return 0; }
輸出結果:
Sentence contains 2 punctuation characters.
相關文章
C++?Boost?CircularBuffer算法超詳細精講
Boost是為C++語言標準庫提供擴展的一些C++程序庫的總稱。Boost庫是一個可移植、提供源代碼的C++庫,作為標準庫的后備,是C++標準化進程的開發(fā)引擎之一,是為C++語言標準庫提供擴展的一些C++程序庫的總稱2022-11-11