颠倒字符串的顺序

Reversing the sequence of a string

本文关键字:顺序 字符串      更新时间:2023-10-16

一个相当简单的程序,试图在C++中反转以null结尾的字符串中的字符,但似乎出了问题。

#include <iostream>
using namespace std;
void reverse(char*);
int main(){
    char *str;
    cout<< "Please enter a string, no spaces please..";
    cin >> str;

    //reverse(str);
}
void reverse(char *str){
    char temp;
    size_t len = strlen(str); 
    for (size_t i = 0; i < len/2; i--)
    {
        temp = str[i];
        str[i] = str[len-i-1];
        str[len-i-1] = temp;
    }
}

获取以下错误

Bus error: 10

感谢您的帮助。

  • 在使用char *str = new char[25]; 之前为str分配内存

  • reverse函数中用于for循环增量i for (size_t i = 0; i < len/2; i++ )

  • 使用delete [] str ; 后取消分配内存

您正在递减迭代器i,而不是递增它

#include <algorithm>
#include <cstring>
void reverse(char* const str)
{
    unsigned long const len = strlen(str);
    for(unsigned long i = 0; i < len >> 1; i++)
        std::swap(str[len - i - 1], str[i]);
}
#include <algorithm>
#include <string>
#include <iostream>
#include <cstring>
int main() {
  // You can't read something to nowhere.
  // String will be holded in static array.
  char str[1024];
  // To keep it as null terminated string after
  // writing of inputed string: `std::cin` don't
  // write null character after writing of data.
  memset(str, 0, 1024);
  std::cin >> str;
  // If you do reversing of strings in C++,
  // you shouldn't use hand written loops: 
  std::reverse(str, str + strlen(str));
  std::cout << str << std::endl;
}

试试这个修改后的代码版本:

#include <iostream>
#include <cstring>
using namespace std;
void reverse(char*);
int main(){
    char str[1024]; // buffer of 1024 chars
    cout<< "Please enter a string, no spaces please..";
    cin >> str;

    reverse(str);
    cout << "nReversed: " << str;
}
void reverse(char *str){
    char temp;
    size_t len = strlen(str); 
    for (size_t i = 0; i < len/2; i++) // loop until half of the user input
    {
        temp = str[i];
        str[i] = str[len-i-1];
        str[len-i-1] = temp;
    }
}

我只是添加了字符char str[1024];的数组来存储用户输入。。并将循环更改为:for (size_t i = 0; i < len/2; i++)

但是,您必须非常小心地使用上面的代码。。如果输入的大小小于数组的固定大小,则它可以正常工作。