checking if character is upper or lower case in alphanumeric

故事扮演 提交于 2019-12-04 20:34:32

For upper-case function just loop trough the string and if a lowercase character is encountred you return false like value. And don't use standard library functions names to name your own functions. Use isUpperCase instead.

Live Demo: 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;
}
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
}

You have a lot to learn, besides using a name of a standard function your design also is completely flawed. You only memorize the case of the last character that you encounter in your for loop, so the result that you return is not at all what you think.

Some more observations:

  • Don't use the name of a standard function for your own.
  • Arrays decay to pointers when then are used as function parameters. You have no way to automatically detect the size of the array.
  • You expect your return from isupper to be a logical value. Testing that again with ==1 makes not much sense.
  • You have two different variables called input, one in file scope, one in main.

Fairly simple:

#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; 
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!