【问题标题】:Checking if string is only letters and spaces检查字符串是否只有字母和空格
【发布时间】:2015-08-22 02:07:14
【问题描述】:

我写了这个简单的代码来检查一个字符串是否只有字母和空格

#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#define N 100

int checkString(char str1[]);

void main()
{
    char str1[N];

    scanf("%s", str1);

    printf("%d",checkString(str1));

    getch();
}

int checkString(char str1[])
{
    int i, x=0, p;
    p=strlen(str1);
    for (i = 0; i < p ; i++)
    {
        if ((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z') || (str1[i] == ' '))
        {
            continue;
        }
        else{ return 0; }
    }
    return 1;
}

当我输入类似以下内容时,这很好用:

hello asds //returns 1

hello1010 sasd  // return 0

但如果我在空格后输入任何内容,它会返回 1,如下所示:

hello 1220  //returns 1

blabla 11sdws // returns 1

谁能告诉我为什么?

【问题讨论】:

  • 你知道%s 只读取第一个字符字符串直到第一个空白字符,对吧?因此,如果您输入"hello 123",那么str 将包含"hello",这符合您对全字母或空格的测试。也许fgets 稍作改动以修剪尾随换行符可能更符合您的要求。
  • 不,我不知道,谢谢你告诉我
  • @WhozCraig 详细信息:"%s" 首先跳过前导空格,然后然后读取(并存储)第一个字符字符串直到第一个空格 char。跨度>

标签: arrays c function char c-strings


【解决方案1】:

如果使用标头&lt;ctype.h&gt;中声明的标准C函数isalphaisblank,可以更简单、更正确地编写函数,例如

#include <ctype.h>

//...

int checkString( const char s[] )
{
    unsigned char c;

    while ( ( c = *s ) && ( isalpha( c ) || isblank( c ) ) ) ++s;

    return *s == '\0'; 
}

如果你想检查一个字符串是否包含空格,那么你应该使用函数isblank而不是函数isspace

考虑到在这样简单的循环中使用语句continue 不是一个好主意。最好在没有continue 语句的情况下重写循环。

如果要输入句子,最好使用函数fgets而不是函数scanf 该函数允许将多个单词作为一个字符串输入,直到按下Enter。

例如

fgets( str1, sizeof( str1 ), stdin );

考虑到函数包含换行符。所以在输入一个字符串后,你应该删除这个字符。例如

size_t n = strlen( str1 );
if ( n != 0 && str1[n-1] == '\n' ) str1[n-1] = '\0';

【讨论】:

    【解决方案2】:

    你忘记了数字

    int checkString(char str1[]) {
        int i, x=0, p;
        p=strlen(str1);
    
        for (i = 0; i < p ; i++)
            if ((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z') || (str1[i] == ' ') || (str1[i] >= '0' && str1[i] <= '9')) {
                continue;
            } else return 0;
    
        return 1;
    }
    

    或者更好

    #include <ctype.h>
    ...
    
    int checkString(char str1[]) {
        int i, x=0, p;
        p=strlen(str1);
    
        for (i = 0; i < p ; i++)
            if (isalnum(str1[i]) || (str1[i] == ' '))
                continue;
            else return 0;
    
        return 1;
    }
    

    【讨论】:

    • 你错过了问题的重点。输入的数字正是 OP 希望函数为诸如“hello 123”之类的字符串返回 0 的原因。问题在于读取字符串的方法,它在第一个空格处停止
    • @WhozCraig buh...是的,我当时肯定错过了。
    【解决方案3】:

    发生这种情况是因为您使用 scanf(%s,&str) 进行输入。在这种输入方式中,仅存储空格 \n 之前的字符或其他空白字符。因此,当您输入空间时,输入仅存储到空间中。

    例如,您输入 hello 1234 您的 str 仅存储 hello 并且 1234 保留在缓冲区中。尝试使用 getchar()。

    #include<stdio.h>
    #include<conio.h>
    #include<math.h>
    #include<stdlib.h>
    #include<string.h>
    #define N 100
    
    int checkString(char str1[]);
    
    void main() 
     {
      char str1[N];
      int i=0;
      while(1)
      {
       str1[i++]=getchar();
       if(str1[i-1]=='\n') break;
       }
      printf("%d",checkString(str1));
      getch();
     } 
    
    int checkString(char str1[])
     {
      int i, x=0, p;
      p=strlen(str1);
      for (i = 0; i < p ; i++)
        {
        if ((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z') || (str1[i] == ' '))
        {
            continue;
        }
        else{ return 0; }
      }
      return 1;
     }  
    

    【讨论】:

      【解决方案4】:

      当你使用scanf("%s",str1);时,你输入hello 112,str1得到的是hello。所以你可以使用fgets(str1,N,stdin);来获取字符串。我认为它会工作。

      【讨论】:

        【解决方案5】:

        您的输入字符串有问题 scanf() 只会将您的输入带到空间,因为它是 whitespace

        因此,当您输入为 hello 1234 时,它正在检查的实际输入是 hello 。通过打印您正在输入的内容(即打印str1)来检查这一点。然后你就会知道这段代码的错误。

        您可以使用getsfgets 来解决问题。

        【讨论】:

          【解决方案6】:

          如果您打印回刚刚 scanf()ed 的字符串,您会注意到它只获取所有输入的第一部分。即空白之后的任何内容,包括空白都被忽略。 您可以使用 getch() (windows) 或 getchar() (linux) 来获取每个字符输入并在您有 "\n" (换行符) 时终止

          来源:http://www.cplusplus.com/reference/cstdio/scanf/

          #include <stdio.h>
          #include <string.h>
          #include <stdlib.h>
          #include <ctype.h>
          
          #define N 100
          
          int checkString(char str1[]);
          
          void main()
          {
              int i = 0;
              int c;
              char str1[N];
          
              memset(str1, 0, sizeof(str1));
          
              do {
                  c = getchar();
                  str1[i++] = c;
              } while ((c != '\n') && (i < (N - 1))); // (i < N - 1) reserves one place for null char
          
              // last char is '\n' - remove it.
              str1[i-1] = 0;
          
              printf("Result: %s\n", checkString(str1) ? "letters and/or spaces only" : "other characters other than spaces and/or letters present");
          }
          
          // expects a null terminated string
          int checkString(char str1[])
          {
              char* p = str1;
          
              while (*p) {
          
                  if (!isalpha(*p) && !isspace(*p)) {
                      return 0;
                  }
                  p++;
              }
          
              return 1;
          }
          

          【讨论】:

            猜你喜欢
            • 2015-06-10
            • 2014-08-03
            • 1970-01-01
            • 2011-07-11
            • 1970-01-01
            • 2010-12-16
            • 1970-01-01
            • 2023-03-23
            相关资源
            最近更新 更多