C++反转一个只有一个字符串的字符串

C++ reversing a string with only one string

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

我试图只使用一个字符串来反转字符串,但当我输出字符串时,它缺少一个字母。是不是有什么我不知道的东西被改写了?这是我的代码:

#include <iostream>
using namespace std;

int main() {
  string d = "jakejosh"; //11 
  char temp = '';
  int j = d.size()/2;
  for (int i=d.size()/2; i> 0; i--) //5
  {
    temp = d[i+j];
    d[j+i] = d[j-i];
    d[j-i] = temp;
  }
  cout << d << endl;
  return 0;
}

输出为:ttam olle

输出应为:ttam olleh

当字符串大小为偶数时,则代码是错误的。例如,如果大小等于2,则size()/2等于1,并且在循环中,您将得到thet d[i+j]等于d[size()/2+size()/2],等于d[2],而索引的有效范围为[0,1]此外,您应该包括标题<string>,并且您可以使用标准函数std::swap

最简单的方法是以下

#include <iostream>
#include <string>
int main() 
{
    std::string s = "hello matt";
    s = std::string( s.rbegin(), s.rend() );
    std::cout << s << std::endl;
    return 0;
}

如果你想自己写循环,那么代码可以看起来像

#include <iostream>
#include <string>
int main() 
{
    std::string s = "hello matt";
    for ( std::string::size_type i = 0; i < s.size() / 2; i++ )
    {
        char c = s[i];
        s[i] = s[s.size()-i-1];
        s[s.size()-i-1] = s[i];
    }
    std::cout << s << std::endl;
    return 0;
}

或者你可以写一些奇特的解决方案。:)例如

#include <iostream>
#include <string>
#include <utility>
int main() 
{
    std:: string s = "Jake Smith"; 
    std::cout << s << std::endl;
    for ( std::string::size_type i = 0, j = s.size(); j - i > 1; i++  )
    {
        std::swap( s[i], s[--j] );
    }
    std::cout << s << std::endl;
    return 0;
}

程序输出为

Jake Smith
htimS ekaJ

或者你可以试着写一个递归函数。

最后可以使用<algorithm>报头中声明的标准算法std::reverse

使用std::reverse()来执行此操作。出于教育目的,请查看以下纯C算法:http://www.programmingsimplified.com/c-program-reverse-string

for (int i=d.size()/2; i> 0; i--) //5
  {
    temp = d[i+j-1]; // d[9] i.e.must be 9 not 10 for swapping with 'h'
    d[j+i-1] = d[j-i];
    d[j-i] = temp;
  }

在原地反转字符串时,很容易出现索引错误。

如果字符串的长度为LEN,则有效索引为0-N-1

在你的情况下,让我们看看中间部分,以及你是如何从那里开始交换的。

hello matt

要反转字符串,您必须交换

hello matt (swap 0-th and 9-th)
^        ^
hello matt (swap 1-st and 8-th)
 ^      ^
hello matt (swap 2-nd and 7-th)
  ^    ^
hello matt (swap 3-rd and 6-th)
   ^  ^
hello matt (swap 4-th and 5-th)
    ^^

i的起始值为(N-1)/2

i的结束值为0

用于交换i处的值的索引是len - 1 - i。(在您的情况下,将d[0]d[9]互换)

把这些放在一起,函数应该是这样的:

void reverse_string(string& d)
{
   int len = d.length();
   for (int i=(len-1)/2; i >= 0; i--)
   {
      int j = len - 1 - i;
      char temp = d[j];
      d[j] = d[i];
      d[i] = temp;
   }
}

下面是测试它的main函数

int main()
{
   string d = "hello matt"; 
   reverse_string(d);
   cout << d << endl;
   d = "hello max"; 
   reverse_string(d);
   cout << d << endl;
   return 0;
}
相关文章: