我必须向用户询问一个句子和一个字符。然后我必须找到该句子中具有该字符的每个单词并打印这些单词。我不能使用 strtok() 这是我目前所拥有的。它几乎可以工作,但不会正确打印单词。有人能帮忙吗?对不起,我是 C 的新手。
#include <stdio.h>
#include <string.h>
int main()
{
char character;
char sentence[] = "this is my first sentence";
char *strPtr;
char word;
//printf("Enter a sentence\n");
//fgets(sentence, 500, stdin);
printf("Enter a character\n");
scanf("%c", &character);
printf("Words containing %c are: \n", character);
strPtr = sentence;
while(*strPtr != '\0')
{
if (*strPtr == character)
{
printf("%s\n", strPtr);
}
strPtr++;
}
return 0;
}
最佳答案
#include <stdio.h>
#include <ctype.h>
int main(void){
char character;
char sentence[] = "this is my first sentence";
char word[sizeof sentence];
char *strPtr, *wordPtr = word;
int contain = 0;
printf("Enter a character\n");
scanf("%c", &character);
printf("Words containing %c are: \n", character);
for(strPtr = sentence; *strPtr != '\0'; strPtr++){
if(isspace(*strPtr)){
*wordPtr = '\0';
if(contain)
printf("%s\n", word);
//reset
contain = 0;
wordPtr = word;
} else {
if(*strPtr == character)
contain = 1;//find
*wordPtr++ = *strPtr;
}
}
*wordPtr = '\0';
if(contain)
printf("%s\n", word);
return 0;
}
关于c - 在句子中查找特定字符并打印具有该字符的每个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29569102/