一个简单的统计一句话里有多少个单词的小程序,请教

如题
比如a="so many things you want!"
统计a中有多少个单词
c ,c++, java,都行。
谢谢

本题的一个完整的c程序如下,程序在win-tc和Dev-c++下都调试通过。
#include<stdio.h>
int main()
{
char str[200];
int i=0,n=0;
printf("Please input a line:");
gets(str);
while(str[i]!='\0')
{
if ((str[i]>='a'&&str[i]<='z'||str[i]>='A'&&str[i]<='Z')&&(str[i+1]==' '||str[i+1]=='\0'||str[i+1]==','||str[i+1]=='?'||str[i+1]=='.'||str[i+1]=='!'))
n++;
i++;
}
printf("There are :%d words.\n",n);
system("pause");
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-12-30
已经编译运行确认,并且考虑到了常用的标点符号的问题:

#include<conio.h>
#include<stdio.h>

void main()
{
int count=0,i=0,flag=0;
char chr[50];

printf("please input the sentence: \n");
gets(chr);

while(*(chr+i)!='\0')
{
if((*(chr+i)!=' ')&&(*(chr+i)!='!')&&(*(chr+i)!='.')) flag=1;
else if(((*(chr+i)==' ')&&(flag==1))||((*(chr+i)==',')&&(flag==1)))
{
count++;
flag=0;
}
i++;
}

if(flag==1) count++;

printf("there are %d words.",count);

getch();
}
第2个回答  2008-12-30
char instr[1024];
scan("%s",inputstr);
int i=0;
in count=0;
while(i < strlen(instr))
{
if(instr[i] == ' ' || instr[i]==',' || instr[i]== '\0') count++
}

printf("这句话单词个数count=%d",count);
第3个回答  2008-12-30
大家都用C,我来下Java吧

public class aaa {
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "so many things you want!";
String[] s = a.split(" ");
System.out.println(s.length);
}
}
第4个回答  2008-12-30
C++ 写的
#include <iostream.h>

bool chartacter(const char c) {
if ((c>='a'&&c<='z')||(c>='A'&&c<='Z'))
return true;
else
return false;
}

int countwords(const char s[]) {
int i, wordcount=0;
bool lookforword=true;
for (i=0; s[i]!='\0'; ++i) {
if (chartacter (s[i])) {
if (lookforword)
++wordcount;
lookforword=false;
} else {
lookforword=true;
}
}
return wordcount;
}

void readline(char line[]) {
int i=0;
char inchar;

do {
inchar=getchar();
//std::cin>>inchar;
line[i]=inchar;
++i;
} while (inchar!='\n');
line[i-1]='\0';
}
int main() {
char text[81];
int totalwords=0;

bool voidchar=false;

cout<<"type in your text.\n"<<endl;
cout<<"when you are done,press 'Enter'"<<endl;

while (!voidchar) {
readline (text);
if (text [0]=='\n')
voidchar=true;
else {
totalwords +=countwords(text);
voidchar=true;
}
}
cout<<"\nThere are "<<totalwords<<" words in the above text."<<endl;
return 0;
}
第5个回答  2008-12-30
题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
1.程序分析:利用while语句,条件为输入的字符不为'\n'.

2.程序源代码:
#include "stdio.h"
main()
{char c;
int letters=0,space=0,digit=0,others=0;
printf("please input some characters\n");
while((c=getchar())!='\n')
{
if(c>='a'&&c<='z'||c>='A'&&c<='Z')
letters++;
else if(c==' ')
space++;
else if(c>='0'&&c<='9')
digit++;
else
others++;
}
printf("all in all:char=%d space=%d digit=%d others=%d\n",letters,
space,digit,others);
}