用字母数字检查字符是大写还是小写
我有这个C代码。 如果我输入LOL123,它应该显示它是大写的。 而且lol123是小写的。 在检查isupper或更低时,如何使用isalpha排除非数字输入?
#include #define SIZE 6 char input[50]; int my_isupper(char string[]); int main(){ char input[] = "LOL123"; int m; m= isupper(input); if( m==1){ printf("%s is all uppercase.\n", input); }else printf("%s is not all uppercase.\n", input); return 0; } int my_isupper(char string[]){ int a,d; for (a=0; a<SIZE); a++){ d= isupper(string[a]) ; } if(d != 0) d=1; return d; }
对于大写函数,只需循环遍历字符串,如果小写字符被装入,则返回false
如值。 并且不要使用标准库函数名来命名您自己的函数。 请改用isUpperCase
。
现场演示: https : //eval.in/93429
#include #include int isUpperCase(const char *inputString); int main(void) { char inputString1[] = "LOL123"; char inputString2[] = "lol123"; printf("%s is %s\n", inputString1, isUpperCase(inputString1)?"upper-case":"not upper-case"); printf("%s is %s\n", inputString2, isUpperCase(inputString2)?"lower-case":"not upper-case"); return 0; } int isUpperCase(const char *inputString) { int i; int len = strlen(inputString); for (i = 0; i < len; i++) { if (inputString[i] >= 'a' && inputString[i] <= 'z') { return 0; } } return 1; }
int my_isalpha_lower(int c) { return ((c >= 'a' && c <= 'z')); } int my_isalpha_upper(int c) { return ((c >= 'A' && c <= 'Z')); } int isdigit(int c) { return (c >= '0' && c <= '9'); } while (*s) { if (!is_digit(*s) && !my_isalpha_lower(*s)) { //isnot lower but is alpha } else if (!is_digit(*s) && !my_alpha_upper(*s)) { //is not upper but is alpha } s++; }
char c = ...; if (isalpha(c)) { // do stuff if it's alpha } else { // do stuff when not alpha }
你需要学习很多东西,除了使用标准function的名称,你的设计也是完全有缺陷的。 你只记住你在for
循环中遇到的最后一个字符的情况,所以你返回的结果根本不是你想的。
更多观察:
- 不要为自己使用标准函数的名称。
- 当数组用作函数参数时,数组会衰减为指针。 您无法自动检测arrays的大小。
- 您希望从
isupper
返回是一个逻辑值。 再次使用==1
进行测试没有多大意义。 - 你有两个不同的变量叫做
input
,一个在文件范围,一个在main
。
相当简单:
#include /** * Will return true if there's at least one alpha character in * the input string *and* all alpha characters are uppercase. */ int allUpper( const char *str ) { int foundAlpha = 0; int upper = 1; for ( const char *p = str; *p; p++ ) { int alpha = isalpha( *p ); foundAlpha = foundAlpha || alpha; if ( alpha ) upper = upper && isupper( *p ); } return foundAlpha && upper; }