isspace() kiểm tra ký tự có phải whitespace character (ký tự khoảng trắng) không. Định nghĩa trong <ctype.h> / <cctype>.
Whitespace characters (Locale "C")
| Ký tự | Escape | ASCII | Tên |
| Space | ' ' | 32 | Khoảng trắng |
| Horizontal tab | \t | 9 | Tab ngang |
| Vertical tab | \v | 11 | Tab dọc |
| Form feed | \f | 12 | Trang mới |
| Carriage return | \r | 13 | Đầu dòng |
| Newline | \n | 10 | Xuống dòng |
Cú pháp
int isspace(int ch);
Ví dụ 1: Đếm khoảng trắng trong string
#include <iostream>
#include <cctype>
using namespace std;
int main() {
char str[] = "Coding is fun";
int count = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (isspace((unsigned char)str[i])) count++;
}
cout << "Số khoảng trắng: " << count << endl; // 2
return 0;
}
Kết quả
Số khoảng trắng: 2
Ví dụ 2: Kiểm tra ký tự đơn
#include <iostream>
#include <cctype>
using namespace std;
int main() {
char ch1 = 'A', ch2 = ' ', ch3 = '\t';
auto check = [](char c) {
cout << "'" << (c == ' ' ? " " : (c == '\t' ? "\\t" : string(1,c)))
<< "': " << (isspace((unsigned char)c) ? "space" : "not space") << '\n';
};
check(ch1); // not space
check(ch2); // space
check(ch3); // space
return 0;
}
Kết quả
'A': not space
' ': space
'\t': space
C++: Locale-aware version
#include <locale>
#include <iostream>
int main() {
char c = ' '; // space
std::locale loc("");
// C locale (chuẩn)
cout << "C locale: " << std::isspace(c, std::locale::classic()) << '\n'; // 1
// User locale
cout << "User locale: " << std::isspace(c, loc) << '\n'; // 1
// Non-breaking space (U+00A0) - trong Latin-1
char nbsp = 0xA0; // Có thể là space trong một số locale
cout << "NBSP C locale: " << std::isspace(nbsp, std::locale::classic()) << '\n'; // 0
cout << "NBSP User locale: " << std::isspace(nbsp, loc) << '\n'; // Có thể 1
return 0;
}
Lưu ý quan trọng
- BẮT BUỘC cast
(unsigned char) khi truyền char biến (tránh UB với signed char)
- Phụ thuộc locale: locale "C" chỉ 6 ký tự trên. Locale khác có thể thêm non-breaking space, etc.
- Khác với
iscntrl(): space (32) KHÔNG phải control char
- C++: có overload trong
<locale> nhận locale parameter
Ứng dụng thực tế
- Tokenizing string (tách từ):
std::istringstream tự dùng isspace
- Trim string (xóa space đầu/cuối)
- Validate input (không cho control char, chỉ cho printable + space)
- Parsing: skip whitespace
C++ Modern: Trim với string_view
#include <string_view>
#include <cctype>
std::string_view trim(std::string_view sv) {
auto not_space = [](char c) { return !std::isspace(static_cast(c)); };
auto first = std::find_if(sv.begin(), sv.end(), not_space);
auto last = std::find_if(sv.rbegin(), sv.rend(), not_space).base();
return first < last ? std::string_view(first, last - first) : std::string_view{};
}