简体   繁体   English

检查 C 中字符串中的任何特殊字符

[英]Check any special characters in a string in C

I tried running this code and it seems that it will only check a characters and not a whole string, if I have a long string like "Adam@", does anyone know how to check like the whole string and not just a character like 'n'.我尝试运行这段代码,它似乎只会检查一个字符而不是整个字符串,如果我有一个像“Adam@”这样的长字符串,有谁知道如何检查整个字符串而不是像'这样的字符n'。

****char ch;
    /* Input character from user */
    printf("Enter any character: ");
    scanf("%c", &ch);
    /* Alphabet check */
    if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
    {
        printf("'%c' is alphabet.", ch);
    }
    else if(ch >= '0' && ch <= '9')
    {
        printf("'%c' is digit.", ch);
    }
    else 
    {
        printf("'%c' is special character.", ch);
    }****
scanf("%c", &ch);

This will only read a single character.这只会读取一个字符。 To read an entire word, use:要阅读整个单词,请使用:

char word[32]; // set size to the maximum word length you want to handle (+1 for null termination)
scanf("%31s", word);

Then use a loop to check every character in the word, such as:然后使用循环检查单词中的每个字符,例如:

for (int i = 0; i < 32; i++) {
    if (char[i] == 0) break;
    // Check word[i]
    ...
}

C language has no direct notion of string. C 语言没有字符串的直接概念。 Only the Standard Library has: by convention, a character string is represented as a null terminated character array.只有标准库具有:按照惯例,字符串表示为 null 终止的字符数组。

So you must:所以你必须:

  1. declare an array large enough the hold the expected strings (say no more than 31 characters)声明一个足够大的数组来保存预期的字符串(比如不超过 31 个字符)

     char word[32]; // 31 chars + 1 terminating null
  2. read a (blank or space delimited) word taking care or not overflowing the array:读取(空白或空格分隔的)单词,注意或不溢出数组:

     scanf("%31s", word);
  3. loop over the characters of that word:循环遍历该单词的字符:

     for (int i=0; i<strlen(word); i++) { char ch = word[i]; // copy here your current code processing ch }

As you would have to use a char array to store this string, you can easily iterate over this array.由于您必须使用 char 数组来存储此字符串,因此您可以轻松地遍历此数组。

Just like htis:就像 htis 一样:

char s[100]; //string with max length 100
/* Input string from user */
printf("Enter any string: ");
scanf("%s", &s);
/* Alphabet check */
for(int i = 0; i <100; i++){
    char ch = s[i];
    if(ch == '\0') break; //stop iterating at end of string
     if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
    {
        printf("'%c' is alphabet.", ch);
    }
    else if(ch >= '0' && ch <= '9')
    {
        printf("'%c' is digit.", ch);
    }
    else 
    {
        printf("'%c' is special character.", ch);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM