反转一个词:C++
Reversing a word : C++
我想在 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:应