用C倒车字符串 [英] Reversing string in C

查看:113
本文介绍了用C倒车字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试建立code,这将扭转串话是这样的:

i try to build code that will reverse the string words like this:

input: Hello World!
output:olleH !dlroW

我不能使用任何指针
在code我建立的是,
还有就是拿到句子列表地址(矩阵,最多20行)的函数 - 表,句子的数量,在表和我想改变句子的数量

i can't use any pointers The code i build is that, There is a function that got the sentences list address (matrix with up to 20 lines) - table, number of the sentences that in the table and the number of the sentence that i want to change.

int changeCharOrder(char table[][MAX_SENTENCE_LENGTH], int numOfSentences, int sentenceToChange) {
    int slen, slen2, slenrev, lastwordlen=0, c=0, i, q, f, start=0;
    char reversed[MAX_SENTENCE_LENGTH]; // the reversed sentence will be here
    char oneword[MAX_SENTENCE_LENGTH];  // i tried to split the sentence to words and then reverse them
    reversed[0] = '\0';
    slen = strlen(table[sentenceToChange]);
    for (i = 0; i < slen; i++) { //for loop to looking for space or EOS
        while((table[sentenceToChange][i] != ' ') && (table[sentenceToChange][i] != '\0')) {
            oneword[c] = table[sentenceToChange][i]; // copy the word and save in oneword
            i++;
            c++;
        }

        oneword[i+1] = '\0';
        slen2 = strlen(oneword);
        slenrev = strlen(reversed);
        for(q = i+slen2-1; q > i; q--){ // here is the reversing code. it's not working well 
            reversed[q-1] = table[sentenceToChange][start];
            start++;
        }
        start++;
        lastwordlen = strlen(oneword);
        reversed[slen] = '\0';
        c = 0;
    }
    reversed[slen] = '\0';
    printf("%s",reversed);  
}

它不工作,因为它是应该的。我能够逆转只有第一个字。
任何建议?谢谢

It's not working as it's should. i able to reverse only the first word. Any advice? thanks

推荐答案

试试这个

for (i=0; i<slen; i++) { //for loop to looking for space or EOS
    while((table[sentenceToChange][i]!=' ')&&(table[sentenceToChange][i]!='\0')) {
        oneword[c] = table[sentenceToChange][i]; // copy the word and save in oneword
        i++;
        c++;
    }

    oneword[i]='\0';
    c--;
    slen2=strlen(oneword);
    slenrev=strlen(reversed);
    for(q=c;c>=0;c--){  //you can remove `q=c` also 'for(;c>=0;c--)' will also work
        reversed[start]=oneword[c]; 
        start++;
    }
    reversed[start++]=' ';
    reversed[start]='\0';
    c=0;
}
printf("\n%s",reversed);

这篇关于用C倒车字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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