輸入一行文本,統計其中單詞數量。單詞定義為由字母組成的連續序列,非字母字符作為分隔符。
#include <stdio.h>
int main() {
char input, prev = ' ';
int count = 0;
while ((input = getchar()) != '\n') {
if (input != ' ' && prev == ' ') // 發現單詞開始
count++;
prev = input;
}
printf("%d\n", count);
return 0;
}
prev 記錄前一字符,初始為空格#include <stdio.h>
#include <ctype.h>
void main() {
char ch;
int wordCount = 0, inWord = 0;
FILE *fp1 = fopen("test.txt", "r");
FILE *fp2 = fopen("result.txt", "w");
if (!fp1 || !fp2) { puts("cannot open file!"); return; }
while ((ch = fgetc(fp1)) != EOF) {
if (isalpha(ch) && !inWord) { inWord = 1; }
else if (!isalpha(ch) && inWord) { wordCount++; inWord = 0; }
}
fprintf(fp2, "%d", wordCount);
fclose(fp1); fclose(fp2);
}
using System;
namespace WordCount {
class Program {
static int CountWords(string str) {
int count = 0;
for (int i = 0; i < str.Length; i++) {
char c = str[i];
if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')))
count++;
}
return count;
}
static void Main() {
string s = "My name is cuihao,what about you?";
Console.WriteLine(CountWords(s));
Console.Read();
}
}
}
| 場景 | 關鍵函數/方法 | 注意事項 |
|---|---|---|
| 標準輸入單行 | getchar() + 狀態變量 | 處理連續空格、制表符等 |
| 文件統計 | fgetc() + isalpha() | 需檢查 EOF,文件指針管理 |
| 字符串統計 | 遍歷字符判斷字母 | C# 用 Char.IsLetter() 更簡潔 |