C语言中的反向词

C语言中的反向词

我正在尝试将句子中单词的字母颠倒过来。我也试图将这些单词存储在一个新的char数组中。目前,我遇到了运行时错误,对于我所有的调整我都无法解决。我的方法是创建一个与句子长度相同的新char数组。然后循环遍历该句子,直到我到达''字符为止。然后向后循环并将这些字符添加到单词中。然后将单词添加到新的句子中。任何帮助将非常感激。

int main(void) {
    char sentence [] = "this is a sentence";
    char *newSentence = malloc(strlen(sentence)+1);
    int i,j,start;
    start = 0;

    for(i = 0; i <= strlen(sentence); i++)
    {

        if(sentence[i] == ' ')
        {
            char *word = malloc((i - start)+1);
            for(j = sentence[i]; j >= start; j--)
            {
                word[j] = sentence[j];
            }
            strcat(newSentence,word);
            start =sentence[i +1];
        }
    }
    printf("%s",newSentence);
    return 0;
}

最佳答案

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    char sentence [] = "this is a sentence";
    char *newSentence;
    int i,j,start, len;
    start = 0;
    len = strlen(sentence);
    newSentence = malloc(len+1);
    *newSentence = '\0';

    for(i = 0; i <= len; i++)
    {
        if(sentence[i] == ' ' || sentence[i] == '\0')
        {
            char *word = malloc((i - start)+1);
            int c = 0;
            for(j = i - 1; j >= start; j--)
            {
                word[c++] = sentence[j];
            }
            word[c]='\0';
            strcat(newSentence,word);
            if(sentence[i] == ' ')
                strcat(newSentence," ");
            start = i + 1;
            free(word);
        }
    }
    printf("%s",newSentence);
    return 0;
}

关于c - C语言中的反向词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16022220/

10-11 23:13