我要问用户一个句子和一个字符。然后我必须找到每个在句子中有这个特征的单词并打印出来。我不能用strtok()这是我目前所拥有的。它几乎可以正常工作,但无法正确打印单词。有人能帮忙吗?对不起,我是新来的。。

#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/

10-10 04:28
查看更多