#include
int main(void)
{
char str[256];
char *cp;
printf("Input sentence:");
gets(str);
for(cp = str; *cp != '\0'; cp++)
{
/* 判断单词首字母是否是大写 */
if((cp == str || *(cp -1) == ' ') && *cp >= 'A' && *cp <= 'Z')
{
while((*cp >= 'A' && *cp <= 'Z') || (*cp >= 'a' && *cp <= 'z'))
{
printf("%c", *cp);
cp++;
}
printf("\n");
}
}
return 0;
}
应用sscanf函数的选择性读取功能和当前读取字符计数功能可方便地解决问题。举例如下:
//#include "stdafx.h"//If the vc++6.0, with this line.
#include "stdio.h"
int main(void){
char sent[200],tmp[21];
int i=0,x;
printf("Please enter an English sentence...sent:\n");
gets(sent);
while(!((x=sent[i]|0x20)>='a' && x<='z'))//跳过前导非字母
i++;
for(;sent[i];i++){
sscanf(sent+i,"%[A-Za-z]%*[^A-Za-z]%n",tmp,&x);//选择性读取并计数
if(*tmp>='A' && *tmp<='Z')//只输出首字母大写的单词
printf("%s\n",tmp);
i+=x-1;//根据刚刚读取的单词长度调整下标
}
printf("\n");
return 0;
}
我写了个完整程序给你参考。
源代码如下(vc++6.0下编译通过):
#include
#include
#define MAX_SENTENCE_STR_LEN 1024
int main()
{
char English_sentence[MAX_SENTENCE_STR_LEN] = {0};
char word[32] = {0};
char *token = NULL;
char *seps = " ";
printf("please input a English sentence: \n");
gets(English_sentence);
token = strtok(English_sentence, seps);
while (token != NULL)
{
strcpy(word, token);
if (word[0] >= 'A' && word[0] <= 'Z')
{
printf("%s\n", word);
}
token = strtok(NULL, seps);
}
return 0;
}
希望对你有帮助。