简体   繁体   English

反转一个词:C ++

[英]Reversing a word : C++

I want to reverse a char string in c++. 我想在C ++中反转一个char字符串。 I wrote this code: 我写了这段代码:

#include <iostream>
#include <string.h>

using namespace std;

int main(){
    char word[80] = "polymorphism";
    char rev[80];
    int i, j;
    int l;
    l = strlen(word);
    for(i = 0, j = l; i < l-1; i++, j--){
        word[j] = rev[i];
    }
    cout << rev << endl;
    return 0;
}

In terminal it shows some characters like this: 在终端中,它显示了一些这样的字符:

83???uH??? ... Something like this

Your character array rev is not zero terminated. 您的字符数组rev不是零终止的。

And istead of to write to rev you are writing to word.:) 而且,您不是在写版本,而是在写单词。:)

    word[j] = rev[i];

The loop is also wrong due to condition 由于条件,循环也是错误的

i < l-1;

There must be 必须有

i < l;

The program can look the following way 该程序可以如下所示

#include <iostream>
#include <cstring>

int main()
{
    char word[80] = "polymorphism";
    char rev[80];

    size_t n = std::strlen( word );

    size_t i = 0;
    for ( ; i < n; i++ ) rev[i] = word[n - i - 1];
    rev[i] = '\0';

    std::cout << word << std::endl;
    std::cout << rev << std::endl;

    return 0;
}

The program output is 程序输出为

polymorphism
msihpromylop

Take into account that you can do the same using standard algorithm std::reverse_copy declared in header <algorithm> . 考虑到您可以使用标头<algorithm>声明的标准算法std::reverse_copy进行相同的操作。 For example 例如

#include <iostream>
#include <cstring>
#include <algorithm>

int main()
{
    char word[80] = "polymorphism";
    char rev[80];

    size_t n = std::strlen( word );

    *std::reverse_copy( word, word + n, rev ) = '\0';

    std::cout << word << std::endl;
    std::cout << rev << std::endl;

    return 0;
}

The program output is the same as above 程序输出与上面相同

polymorphism
msihpromylop
#include <iostream>
#include <string.h>

using namespace std;

int main(){
    char word[80] = "polymorphism";
    char rev[80] = {'\0'};
    int i = 0;
    int last = strlen(word) - 1;
    while(last >= 0) {
        rev[i] = word[last];
        i++;
        last--;
    }
    cout << rev << endl;
    return 0;
}

There are 3 changes I made to your code: 我对您的代码进行了3处更改:
Change 1: Since string length is l , indexing will be from 0 to l-1 . 更改1:由于字符串长度为l ,因此索引从0l-1
Change 2: rev will be storing the values from word , not the other way round. 变更2: rev将存储word的值,而不是相反。
Change 3: A proper string should be \\0 terminated. 更改3:正确的字符串应以\\0终止。

#include <iostream>
#include <string.h>

using namespace std;

int main(){
char word[80] = "polymorphism";
char rev[80]="";
int i, j;
int l;
l = strlen(word);
for(i = 0, j = l-1; i < l; i++, j--){    //change 1
    rev[i] = word[j];                     // change 2   
}
rev[i]='\0';          // change 3 

cout<<rev;
return 0;
}

Working ideone link: http://ideone.com/kIqeNF 可用的ideone链接: http ://ideone.com/kIqeNF

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM