Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to reverse the letters for words in a sentence. I am also trying to store these words in a new char array. At the moment I getting a runtime error, which for all my tweaking I can not solve. My approach is to create a new char array the same length as the sentence. Then loop through the sentence until I reach a ' ' character. Then loop backwards and add these characters to a word. Then add the word to the new Sentence. Any help would be much appreciated.

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
168 views
Welcome To Ask or Share your Answers For Others

1 Answer

#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 = '';

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...