反转一个词:C++

Reversing a word : C++

本文关键字:一个 C++      更新时间:2023-10-16

我想在 c++ 中反转一个字符字符串。我写了这段代码:

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

在终端中,它显示一些字符,如下所示:

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

您的字符数组 rev 不是以零终止的。

而写信就是写字

:)

    word[j] = rev[i];

由于条件原因,循环也错误

i < l-1;

一定有

i < l;

该程序可以如下所示

#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] = '';
    std::cout << word << std::endl;
    std::cout << rev << std::endl;
    return 0;
}

程序输出为

polymorphism
msihpromylop

考虑到您可以使用在标头<algorithm>中声明的标准算法std::reverse_copy执行相同的操作。例如

#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 ) = '';
    std::cout << word << std::endl;
    std::cout << rev << std::endl;
    return 0;
}

程序输出与上述相同

polymorphism
msihpromylop

我对你的代码做了 3 个更改:
更改 1:由于字符串长度为 l ,索引将从 0 t o l-1 开始。
更改 2:rev将存储来自 word 的值,而不是相反。
更改 3:应终止正确的字符串。

#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]='';          // change 3 
cout<<rev;
return 0;
}

工作 ideone 链接:http://ideone.com/kIqeNF

#include <iostream>
#include <string.h>
using namespace std;
int main(){
    char word[80] = "polymorphism";
    char rev[80] = {''};
    int i = 0;
    int last = strlen(word) - 1;
    while(last >= 0) {
        rev[i] = word[last];
        i++;
        last--;
    }
    cout << rev << endl;
    return 0;
}