【问题标题】:function for string statistics字符串统计函数
【发布时间】:2014-05-26 16:42:45
【问题描述】:

任务如下。 实现函数 char* stringstat(const char* s),它将计算字符、数字、空格字符和不可打印字符的数量,并以以下形式输出结果字符串:字符:w 数字:x 空格:y 非打印: z,其中 w,x,y 和 z 是相应的量。 到目前为止,我已经收集了这种原材料。

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

using namespace std;

int main(void)
{
    char str[]="something.-21";
    int length = strlen(str);

    printf("The ASCII value of %c is %d ",character,storeAscii);
    if (storeAscii>=65 && storeAscii<=90)
    {
        printf("\nYou have entered a capital letter");
    }
    else if (storeAscii>=97 && storeAscii<=122)
    {
        printf("\nYou have entered a small letter");
    }
    else if (storeAscii>=47 && storeAscii<=57)
    {
        printf("\nYou have entered a digit ");
    }
    else if (storeAscii>=0 && storeAscii>=47
          || storeAscii>=54 && storeAscii<=64
          || storeAscii>=91 && storeAscii<=96
          || storeAscii>=123 && storeAscii<=127)
    {
        printf("\nYou have entered a special character");
    }

    return 0;
}

我知道我必须有“for”循环来检查字符串中的每个符号,并在符号上挂起添加 count++,然后我可以输出数量。我真的不知道如何对字符串进行循环检查。

非常感谢 timrau 与任务对应的最终产品是这样的:

#include<stdio.h>
#include<string.h>
#include <cctype>
int main()
{
  char str[]="This sentence is messed up. It has 32413523.";
  int w = strlen(str);
  int x=0,y=0,z=0;

  for(char *ptr = str; *ptr!='\0';++ptr)
  {
      if(isdigit(*ptr)){x++;}
      else if(isblank(*ptr)){y++;}
      else if(isprint(*ptr)){z++;}
  }
    printf("In sentence \"%s\" there is:\n",str);
    printf("Characters: %d\n",w);
    printf("Digits: %d\n",x);
    printf("Space characters: %d\n",y);
    printf("Non-printable characters: %d\n",z);
return 0;
}

【问题讨论】:

  • 这不是 C,这是(写得不好,C-ish)C++。

标签: c++ string


【解决方案1】:
#include <cctype>

for (char *ptr = str; *ptr != '\0'; ++ptr)
{
    if (isupper(*ptr)) { /* upper case */ }
    else if (islower(*ptr)) { /* lower case */ }
    else if (isdigit(*ptr)) { /* decimal digit */ }
    else { /* special */ }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 2015-04-02
    • 2013-11-02
    • 2018-01-06
    • 1970-01-01
    相关资源
    最近更新 更多