Home > Software design >  Check if string contains lowercase and uppercase without libraries and regex
Check if string contains lowercase and uppercase without libraries and regex

Time:10-24

I'm a beginner programmer and a have this problem that I'm unable to solve. My assignment is to create a password checking program, which woud take unlimited amount of passwords from stdin (in a file and read every line as a separate password) and test them on four different levels of security. We can't use string.h, ctype.h, malloc, free...

I'm stuck at the first level, which is "test that password includes both lowercase and uppercase letters. I was able to check if it contains at least one of those, or if it is only comprised of combinations of two, with the code below, but I'm lost beyond that. Please, help.

while (string[i] != '\0')
{
    if (isChar_abc(string[i]) == false)
    {
        if (isChar_ABC(string[i]) == true)
        {
            i  ;
        }
        else if (isChar_ABC(string[i]) == false)
        {
            printf("Error, end code\n");
            return 0;
        }
    }
    else if (isChar_ABC(string[i]) == false)
    {
        if (isChar_abc(string[i]) == true)
        {
            i  ;
        }
        else if (isChar_abc(string[i]) == false)
        {
            printf("Error, end code\n");
            return 0;
        }
    }
}

CodePudding user response:

to check if it contains both iterate over the string and set flags if each is found

char containsboth(char* str) {

    int   i;
    char  lower = false, upper = false;

    for (int i = 0; str[i] != '\0'; i  ) {
        lower = lower || (str[i] >= 'a' && str[i] <= 'z');
        upper = upper || (str[i] >= 'A' && str[i] <= 'Z');

        if (lower && upper) break;
    }

    return (lower && upper);

}

check: C programming: How to check whether the input string contains combination of uppercase and lowercase

CodePudding user response:

OP's code uses i ; to count both upper and lower case letters.

Supposedly a final if (i >= 2 /* or 1 */) occurs, yet that does not detect if both upper and lower occurred.

Better to use 2 different i

upper_i  ;
...
lower_i  ;

Sample code simplification:

int contains_upper_and_lower(const char *string) {
  int contains_upper = 0;
  int contains_lower = 0;

  int i;
  while (string[i]) {
    if (isChar_ABC(string[i])) contains_upper = 1;
    else if (isChar_abc(string[i])) contains_lower = 1;
    i  ;
  }
  return contains_upper && contains_lower;
}
  • Related