1 /** 2 * Main.c 3 * 循環-06. 統計一行文本的單詞個數 4 * Created on: 2014年7月25日 5 * Author: Boomkeeper 6 ******測試通過************ 7 */ 8 9 #include <stdio.h> 10 11 int main(){ 12 char input,b=' '; 13 int count=0; 14 15 while((input=getchar())!='\n'){ 16 // printf("%c\n",input); 17 if(input!=' ' && b==' ') 18 count++; 19 b=input; 20 } 21 22 printf("%i\n",count); 23 24 return 0; 25 }
參考來源:
http://tieba.baidu.com/p/3078959002
題目鏈接:
http://pat.zju.edu.cn/contests/basic-programming/%E5%BE%AA%E7%8E%AF-06
#include<stdio.h>
#include<ctype.h>
void main()
{
char ch;
int numberofword=0,wordStart=0;
FILE *fp1 = fopen("test.txt","r");
FILE *fp2 = fopen("result.txt", "w");
if( fp1==NULL || fp2==NULL )
{
puts("cannot open file!");
return;
}
while( !foef(fp1) )
{
ch =fgetc(fp1);
if( isalpha(ch) && wordStart==0 )
{
wordStart = 1;
}
else if( !isalpha(ch) && wordStart==1 )
{
numberofword++;
wordStart = 0;
}
}
fprintf(fp2,"%d",numberofword);
fclose(fp1);
fclose(fp2);
}
思路是遍歷所有的字符,一旦發現非字母字符,那麼+1單詞數~~~
下面是C#代碼。
----------------------------------------------------------
using System;
using System.Collections.Generic;
namespace lianxi
{
class MainClass
{
public static void Main(string[] args)
{
string str1;
str1 = "My name is cuihao,what about you?";
Console.WriteLine(word(str1));
Console.Read();
}
public static int word(string strg)
{
char[] str1 = strg.ToCharArray();
int i,j=0;
for(i=0;i<str1.Length;i++)
{
if(!
(
(str1[i]>=65 && str1[i]<=90)||
(str1[i]>=97 && str1[i]<=122)
)
)
{
j++;
}
}
return j;
}
}
}