(用C程序编写)输入一行字符,统计其中有多少个单词,单词之间用空格分隔开。

如题所述

//这个程序的目的是分割字符串,把一个长字符串分割成许多字串
//就像把一句话分割成一个一个词一样
//程序把相连的字母的数字看成一个词
//例如:输入: 234ui fb*ff
//输出: 234ui
// fb
// ff
#include<iostream>
#include<ctype.h>
#include<string.h>
bool GetWord(char* theString,
char* word, int & wordOffset);
int main()
{
const int bufferSize = 255;
char buffer[bufferSize+1];
char word[bufferSize+1];
int wordOffset = 0;
std::cout << "Enter a string: ";
std::cin.getline(buffer,bufferSize);
while (GetWord(buffer,word,wordOffset))
{
std::cout << "Got this word: " << word << std::endl;
}
return 0;
}
bool GetWord(char* theString, char* word, int& wordOffset)
{
if (!theString[wordOffset])
return false;
char *p1, *p2;
p1 = p2 = theString+wordOffset;
for (int i = 0; i<(int)strlen(p1) && !isalnum(p1[0]);i++)
p1++;
if (!isalnum(p1[0]))
return false;
p2 = p1;
while (isalnum(p2[0]))
p2++;
int len = int (p2 - p1);
strncpy (word,p1,len);
//由于c语言中字符串是以\0结尾的,所以把生成的子串结尾赋为\0
word[len]='\0';
for (int j = int(p2-theString);j<(int)strlen(theString)&& !isalnum(p2[0]);j++)
{
p2++;
}
wordOffset = int(p2-theString);
return true;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-11-11
代码多点,不过准确性高:

#include <stdio.h>
main()
{
char a[100];
int i,count=0,flag=1;
gets(a);
for(i=0;a[i];i++)
{
if((a[i]>='a' && a[i]<='z') || (a[i]>='A' && a[i]<='Z'))
{
flag=0;
continue;
}

if(!flag)
{
count++;
flag=1;
}
}
i--;
if((a[i]>='a' && a[i]<='z') || (a[i]>='A' && a[i]<='Z'))
count++;
printf("%d\n",count);
}
第2个回答  2013-11-11
#include <iostream.h>
void main ()
{
char tmp[30];
int sum = 0;
while (cin >> tmp)
sum++;
cout << sum << endl;
}
输入以ctrl+z然后回车结束。
第3个回答  2013-11-11
#include <stdio.h>
void main()
{
char str[100];
int num=0;
int i=0;

gets(str);
while(str[i] != '\0')
{
while(str[i] == ' ')
{
i++;
}
if(str[i] == '\0')
break;
else
num++;
while(str[i] != ' '&&str[i] != '\0')
{
i++;
}
}
printf("%d\n",num);
}本回答被网友采纳
相似回答