有没有一种方法可以检查数组中字符串的大写和isalpha大小写?

时间:2019-04-21 10:33:35

标签: c

while(1)
    {

        char buff[1000];
        printf("Enter the word: ");
        fgets(buff, 1000, stdin);
        if(!strcmp(buff, "\n"))//empty search then break the loop
        {
            fprintf(stderr, "Exiting the program\n");
            break;
        }


        int error = 0;
        int i = 0;
        while(buff[i] != '\0')
        {

            if(buff[i] >= 33 && buff[i] <= 96)
            {
                break;
            }

            error = 1;
            i++;
        }

        if(error == 0)
        {
            fprintf(stderr, "Please enter something containing only lower-case letters\n");
        }

        }



我希望hello World的输出为Please enter something containing only lower-case letters,但没有收到该错误。 如果输入World hello,将得到预期的结果,它会显示错误消息。

是否可以在整个数组中使用isalpha?

2 个答案:

答案 0 :(得分:1)

有用于检查大小写的库函数。它们分别称为isupperislower。使用它们。尽管'a'不同于97的情况并不常见,但它可能会发生。如果您是指字母'a',请使用字符常量'a'而不是数字97。此外,甚至不能保证字母是连续的,因此不能保证'z'-'a'是字母计算结果为22。但是,数字必须是连续的,因此'9'-'0'将始终计算为9。但是,依靠isalpha之类的库函数要安全得多。我在这里写过关于编码的文章:https://stackoverflow.com/a/46890148/6699433

要更正错误,您需要适当的条件。根据您的问题,如果任何字符都不是小写字母或空格,它将打印错误消息。此外,您的代码过于复杂。这是一个解决方案:

int i = 0;
while(buff[i] != '\0') {
    if(!(islower(buff[i]) || isspace(buff[i]))) {
        fprintf(stderr, "Please enter something containing only lower-case letters\n");
        break;
    }
    i++;
}
  

是否可以在整个数组中使用isalpha?

C没有内置的功能,但是您可以编写自己的映射器。

/* Apply function f on each of the elements in str and return false
 * if f returns false for any of the elements and true otherwise.
 */

bool string_is_mapper(const char *str, size_t size, int (*f)(int c))
{
    for(int i=0; i<size && str[i] != '\0'; i++)
        if(!f(str[i])) return false;
    return true;
}

现在,您可以像这样使用此映射器:

if(string_is_mapper(str, strlen(str), isupper)
     puts("All characters in str is upper case");

您甚至可以将自己的函数编写到插件中,只要它们适合此原型即可:

int condition(int c);

答案 1 :(得分:1)

您不应对字母值进行硬编码,而应使用实际值。在此问题中,'a''z'范围之外的任何字母都是无效的。但是使用库函数isalpha()islower()更方便,因为不能保证字母值是连续的。

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

int main(void)
{
    while(1) {

        char buff[1000];
        printf("Enter the word: ");
        fgets(buff, sizeof buff, stdin);
        if(!strcmp(buff, "\n")) {
            fprintf(stderr, "Exiting the program\n");
            break;
        }
        int error = 0;
        int i = 0;
        while(buff[i] != '\0') {
            if(isalpha(buff[i]) && !islower(buff[i])) {
                error = 1;
                break;
            }
            i++;
        }
        if(error == 1) {
            fprintf(stderr, "Please enter something containing only lower-case letters\n");
        }
    }
}

计划会议

Enter the word: hello world
Enter the word: Hello world
Please enter something containing only lower-case letters
Enter the word: hello World
Please enter something containing only lower-case letters
Enter the word: hello, world!
Enter the word:
Exiting the program