A-Z, a-z) 或底線 _0-9)、底線int, for, while 等)__xxx)、底線+大寫開頭 (_Xxxx) 由實作保留多數線上判題題目(如 HDOJ 1028 / ZOJ 1199)僅檢查:
#include <ctype.h>
#include <stdbool.h>
bool is_valid_identifier(const char *s) {
if (!s || !*s) return false; // 空字串
if (!isalpha((unsigned char)*s) && *s != '_') return false; // 首字元
for (++s; *s; ++s) {
if (!isalnum((unsigned char)*s) && *s != '_') return false;
}
return true;
}
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
int T;
char str[55];
scanf("%d", &T);
getchar(); // 吸收換行
while (T--) {
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // 去除換行
bool ok = true;
if (!isalpha(str[0]) && str[0] != '_') ok = false;
for (int i = 1; ok && str[i]; ++i) {
if (!isalnum(str[i]) && str[i] != '_') ok = false;
}
puts(ok ? "yes" : "no");
}
return 0;
}
輸入: 3 12ajf fi8x_a ff ai_2 輸出: no yes no
解析:12ajf 以數字開頭 ❌;fi8x_a 合法 ✅;ff ai_2 含空格 ❌。
scanf("%s") 會在空格處截斷,必須用 fgets 或 gets 讀整行ctype.h 函數參數需轉 unsigned char 避免負值未定義行為^[A-Za-z_][A-Za-z0-9_]*$(不含關鍵字檢查)。