C语言中的反向词 [英] Reverse words in C Language

查看:73
本文介绍了C语言中的反向词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}

推荐答案

#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语言中的反向词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆