我需要一种方法来检查字符串是否只包含字母字符.由于我在程序中需要多次使用该功能,因此我认为将它放入函数是个好主意.
这是我的实现:
int sisalpha(const char *s) {
int result = 1;
while (s++ != '\0') {
result = isalpha(*s); // uses isalpha of <ctype.h>
if (result == 0) {
return result;
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
我能在这里改进什么?传递某种大小以避免缓冲区溢出并允许检查"子串"是否有益?
您可以通过不必要地存储结果来缩短它.我通常认为简洁的代码是一种改进:
int sisalpha(const char *s) {
while (*s++ != '\0')
if (!isalpha(*s))
return 0;
return 1;
}
Run Code Online (Sandbox Code Playgroud)
我相信这不能检查字符串中的第一个字符.您可以通过将isalpha测试移动到while条件来缩短它,这也可以确保检查第一个字符:
int sisalpha(const char *s) {
while (isalpha(*s))
++s;
return *s == '\0';
}
Run Code Online (Sandbox Code Playgroud)