習題6-1 分類統計字符個數 (15分)


本題要求實現一個函數,統計給定字符串中英文字母、空格或回車、數字字符和其他字符的個數。

  • 小知識:
    c語言'\0' 意思:
    字符常量占一個字節的內存空間。字du符串常量占的內存字節數zhi等於字符串中dao字節數加1。增加的一個字節中存放字符"\0" (ASCII碼為0)。這是字符串結束的標志。

所以原來的這塊:

int n = strlen(s);
for (int i = 0; i < n ; i ++ )

就可以改成:

for (int i = 0; s[i] != '\0' ; i ++ )
  • code
#include <stdio.h>
#include <string.h>
#define MAXS 15

void StringCount( char s[] )
{
    int letter = 0, blank = 0, digit = 0, other = 0;

    int n = strlen(s);

    for (int i = 0; i < n ; i ++ )
    {
        if(s[i] >= '0' && s[i] <= '9') digit += 1;
        else if (s[i] == ' ' || s[i] == '\n') blank += 1;
        else if ( (s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'a' && s[i] <= 'z')) letter += 1;
        else other += 1;
    }

    printf("letter = %d, blank = %d, digit = %d, other = %d", letter, blank, digit, other);

}

void ReadString( char s[] ); /* 由裁判實現,略去不表 */

int main()
{
    char s[MAXS];

    ReadString(s);
    StringCount(s);

    return 0;
}

/* Your function will be put here */


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM