ฟังก์ชัน isspace() เป็นฟังก์ชันที่กำหนดไว้ล่วงหน้าใน ctype.h ระบุว่าอาร์กิวเมนต์เป็นอักขระช่องว่างหรือไม่ อักขระช่องว่างบางตัว ได้แก่ ช่องว่าง แท็บแนวนอน แท็บแนวตั้ง เป็นต้น
โปรแกรมที่ใช้ฟังก์ชัน isspace() โดยการนับจำนวนช่องว่างในสตริงจะได้รับดังนี้ -
ตัวอย่าง
#include <iostream> #include <ctype.h> using namespace std; int main() { char str[] = "Coding is fun"; int i, count = 0; for(i=0; str[i]!='\0';i++) { if(isspace(str[i])) count++; } cout<<"Number of spaces in the string are "<<count; return 0; }
ผลลัพธ์
ผลลัพธ์ของโปรแกรมข้างต้นเป็นดังนี้ −
Number of spaces in the string are 2
ในโปรแกรมข้างต้น ขั้นแรกให้กำหนดสตริง จากนั้นใช้ for loop เพื่อตรวจสอบอักขระแต่ละตัวในสตริงเพื่อดูว่าเป็นอักขระ white space หรือไม่ หากเป็นเช่นนั้น การนับจะเพิ่มขึ้น 1 ในที่สุด ค่าของการนับจะปรากฏขึ้น ซึ่งแสดงอยู่ในตัวอย่างโค้ดต่อไปนี้ −
char str[] = "Coding is fun"; int i, count = 0; for(i=0; str[i]!='\0';i++) { if(isspace(str[i])) count++; } cout<<"Number of spaces in the string are "<<count;
นี่เป็นอีกโปรแกรมหนึ่งที่แสดงฟังก์ชัน isspace() ระบุว่าอักขระที่กำหนดเป็นอักขระช่องว่างหรือไม่ โปรแกรมจะได้รับดังนี้ −
ตัวอย่าง
#include <iostream> #include <ctype.h> using namespace std; int main() { char ch1 = 'A'; char ch2 = ' '; if(isspace(ch1)) cout<<"ch1 is a space"<<endl; else cout<<"ch1 is not a space"<<endl; if(isspace(ch2)) cout<<"ch2 is a space"<<endl; else cout<<"ch2 is not a space"<<endl; return 0; }
ผลลัพธ์
ผลลัพธ์ของโปรแกรมข้างต้นเป็นดังนี้ −
ch1 is not a space ch2 is a space
ในโปรแกรมข้างต้น มีการกำหนด ch1 และ ch2 จากนั้น isspace() ใช้เพื่อตรวจสอบว่าเป็นอักขระช่องว่างหรือไม่ ข้อมูลโค้ดสำหรับสิ่งนี้จะได้รับดังนี้ −
char ch1 = 'A'; char ch2 = ' '; if(isspace(ch1)) cout<<"ch1 is a space"<<endl; else cout<<"ch1 is not a space"<<endl; if(isspace(ch2)) cout<<"ch2 is a space"<<endl; else cout<<"ch2 is not a space"<<endl;