用字母数字检查字符是大写还是小写

时间:2014-01-22 16:39:41

标签: c char uppercase

我有这个C代码。如果我输入LOL123,它应该显示它是大写的。而lol123则是小写的。在检查isupper或更低时,如何使用isalpha排除非数字输入?

#include <stdio.h>

#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;
}

5 个答案:

答案 0 :(得分:2)

对于大写函数,只需循环遍历字符串,如果小写字符被装入,则返回false之类的值。并且不要使用标准库函数名来命名您自己的函数。请改用isUpperCase

现场演示:https://eval.in/93429

#include <stdio.h>
#include <string.h>

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;
}

答案 1 :(得分:2)

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++;

}

答案 2 :(得分:0)

char c = ...;
if (isalpha(c))
{ 
     // do stuff if it's alpha
} else {
     // do stuff when not alpha
}

答案 3 :(得分:0)

你需要学习很多东西,除了使用标准功能的名称,你的设计也是完全有缺陷的。您只记住在for循环中遇到的最后一个字符的大小写,因此您返回的结果根本不是您想的。

更多观察结果:

  • 请勿使用自己的标准功能名称。
  • 当用作函数参数时,数组衰减为指针。您无法自动检测阵列的大小。
  • 您希望从isupper返回的是合乎逻辑的值。再次使用==1进行测试没有多大意义。
  • 您有两个名为input的变量,一个在文件范围内,一个在main

答案 4 :(得分:0)

相当简单:

#include <ctype.h>

/**
 * 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; 
}