【问题标题】:How to print a word with specific character in C?如何在C中打印具有特定字符的单词?
【发布时间】:2018-04-03 07:17:26
【问题描述】:

示例输入:堆栈溢出很棒

要搜索的字符:e

输出:Overflow Awe一些

我写了一个代码,用空格分割字符串并存储为单词,但我不知道如何检查和打印结果

#include <stdio.h>
#include <string.h>
int main()
{
char str1[100];
char newString[10][10]; 
int i,j,ctr;
   printf("\n\n Split string by space into words :\n");
   printf("---------------------------------------\n");    

printf(" Input  a string : ");
fgets(str1, sizeof str1, stdin);    

j=0; ctr=0;
for(i=0;i<=(strlen(str1));i++)
{
    // if space or NULL found, assign NULL into newString[ctr]
    if(str1[i]==' '||str1[i]=='\0')
    {
        newString[ctr][j]='\0';
        ctr++;  //for next word
        j=0;    //for next word, init index to 0
    }
    else
    {
        newString[ctr][j]=str1[i];
        j++;
    }
}
printf("\n Strings or words after split by space are :\n");
for(i=0;i < ctr;i++)
    printf(" %s\n",newString[i]);
return 0;
}

【问题讨论】:

    标签: c arrays string multidimensional-array compare


    【解决方案1】:

    您可以使用strchr() 轻松检查特定字符的字符串

    for (i = 0; i < ctr; i++) {
        if (strchr(newString[i], 'e') != NULL) {
            printf(" %s\n", newString[i]);
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      在您的代码末尾添加以下行以按字符打印过滤的字符串/单词e

      printf("\n Strings or words Containing character 'e' :\n");
      for(i=0;i < ctr;i++)
         if(strchr(newString[i], 'e') != NULL) 
            printf(" %s\n",newString[i]);
      

      【讨论】:

        【解决方案3】:

        既然您正在解析 str1 以查找每个单词的开头和结尾,为什么不使用 for 循环来检测当前单词是否包含您搜索的字母?

        还有很多小“错误”:不要在for循环中使用“strlen”,每次都会调用它!相反,检测 '\0' ! 您的结果数组 newString 不安全!它应该是 [50][100] 因为您可以输入一个包含 100 个字符(因此 [1][100] )或 50 个字母和 50 个空白(因此 [50][2] )的单词的字符串。所以结果数组必须是 [50][100] 才能采取任何可能性。

        【讨论】:

          【解决方案4】:

          我建议使用strtok 拆分字符串并使用strchr 检查子字符串是否包含字母e。通过这种方式,您可以在原始字符串上循环一次并执行拆分和检查。 像这样的:

          #include <stdio.h>
          #include <string.h>
          
          int main ()
          {
              char str[] ="Stack Overflow is Awesome";
              char* pch;
              char* pch2;
              //split string by spaces
              pch = strtok (str," ");
              while (pch != NULL)
              {
                  //check if the substring contains the letter 'e'
                  pch2 = strchr(pch,'e');
                  if (pch2 != NULL) {
                      printf ("%s\n",pch);
                  }
                  pch = strtok (NULL, " ");
              }
              return 0;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-05-06
            • 2015-07-30
            • 2016-12-06
            • 1970-01-01
            • 2022-11-13
            • 2018-11-23
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多