我做错了什么?反向字符串 C++

what am i doing wrong?reverse string c++

本文关键字:字符串 C++ 错了 什么      更新时间:2023-10-16

所以我想在 c++ 中做最简单的事情,反转字符串(存储新字符串(并打印它

我的代码是:

char a[size] , reverse[size];
strcpy(a,"dlow olleh " );
for (int i = 0 ;  i <= strlen(a); i++) {
reverse[i]= a[strlen(a)-i];
}
cout << reverse ;

我必须指出,当 <<反转[i] ; 在 for 循环内,一切都很好,但是当我想将其打印为字符串时,它就是没有,我无法忍受我错过的东西 反转<<[i] ;

我做错了什么?

您正在使用 C 标准库的char数组和函数来操作 C++ 中的字符串。

#include <string>
#include <algorithm>
#include <iostream>
int main()
{
std::string foo{ "Hello, World!" };
std::string bar{ foo };
std::reverse(bar.begin(), bar.end());
std::cout << '"' << foo << "" ==> "" << bar << ""n";
}

如果 - 出于某种超出我理解的原因 - 你*必须*步行完成,以惯用的方式进行,并提供一个接受一对迭代器的接口:

#include <algorithm>
void str_reverse(char *begin, char *end)
{
while (begin < end)
std::swap(*begin++, *--end);
}
// ...
#include <cstring>
// ...
char foo[]{ "Hello, World!" };
str_reverse(foo, foo + std::strlen(foo));

如果出于任何原因无法使用<algorithm>,请实现自己的swap()

template<typename T>
void swap(T &a, T &b)
{
T tmp{ a };
a = b;
b = tmp;
}

在此循环中

for (int i = 0 ;  i <= strlen(a); i++){
reverse[i]= a[strlen(a)-i];

您正在访问字符串的实际字符之外的字符。

例如,当i等于 0 时,您将字符串a终止零字符复制到字符串reverse的第一个位置。

reverse[0]= a[strlen(a)-0];

代码可以编写得更简单,而无需例如对函数strlen进行冗余调用。

char a[size], reverse[size];
strcpy( a, "dlrow olleh" );
size_t i = 0;
for ( size_t n = strlen( a ); i < n; i++ ) 
{
reverse[i] = a[n - i - 1];
}
reverse[i] = '';
std::cout << reverse << 'n';

请注意,有执行相同任务的标准算法std::reverse_copy

下面是一个演示程序。

#include <iostream>
#include <algorithm>
#include <cstring>
int main() 
{
const size_t SIZE = 20;
char a[SIZE], reverse[SIZE];
std::strcpy( a, "dlrow olleh" );    
std::cout << a <<'n';
auto it = std::reverse_copy( a, a + strlen( a ), reverse );
*it = '';
std::cout << reverse <<'n';
return 0;
}

程序输出为

dlrow olleh
hello world

反转字符串时复制的第一个实际上是空终止符,因此当您将其打印到控制台时,它不会显示,因为空终止符是数组中的第一个,所以你想这样做

int size = 12;
char a[12], reverse[12];
strcpy(a, "dlow olleh ");
for (int i = 0; i < strlen(a); i++) {
reverse[i] = a[strlen(a) - (i+1)];
}
reverse[strlen(a)] = '';
cout << reverse;