gpt4 book ai didi

c - 在句子中查找特定字符并打印具有该字符的每个单词

转载 作者:太空宇宙 更新时间:2023-11-04 03:39:51 25 4
gpt4 key购买 nike

我必须向用户询问一个句子和一个字符。然后我必须找到该句子中具有该字符的每个单词并打印这些单词。我不能使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com