【问题标题】:Reverse a string C++ [closed]反转字符串C++ [关闭]
【发布时间】:2020-12-18 12:59:07
【问题描述】:

我是编程新手。我今天学会了如何反转字符串。我尝试使用字符串而不是字符,但终端给出了错误。

string name = { "george" };
int nChar = sizeof(name) - 1;
string *pName = &name;
string *pNameLast = &name + nChar - 1;

while(pName < pNameLast) {
    string save = *pName;
    *pName = *pNameLast;
    *pNameLast = save;
    
    pName++;
    pNameLast--;
}

cout << name << endl;

【问题讨论】:

  • 请在问题中包含错误。注意有一个算法std::reverse,我猜你想去手写吧?
  • 您打算使用string *pNameLast = &amp;name + nChar - 1; 实现什么目标?你知道那是做什么的吗?好像您只是用string 替换了char 的每个实例。
  • 提示 - 你不能只用 std::string 替换 char* 并期望你的代码能够工作。
  • 我建议你投资some good books来正确学习C++。甚至可以上几节课。
  • 这能回答你的问题吗? How do you reverse a string in place in C or C++?

标签: c++ string char reverse


【解决方案1】:

这是使用std::reverse_interator 的示例。这是更好的一种更好的方法。而不是自己做。

#include <iostream>
#include <string>
#include <iterator>
 
int main()
{
    std::string s = "George";
    std::reverse_iterator<std::string::iterator> r = s.rbegin();
    std::string rev(r, s.rend());
    std::cout << rev << endl;
}

【讨论】:

【解决方案2】:

问题:

当您尝试执行string *pName = &amp;namestring *pNameLast = &amp;name + nChar - 1;,您将std::string 视为char*。您不能这样做并期望代码能够正常工作。

解决方案:

std::string 视为std::string。而不是 string *pName = &amp;namepName 声明为 int 并使用 std::string 的运算符 [] 来访问这些值。与pNameLast 类似。您还必须将string save 声明为char,或者我更喜欢使用std::swap 函数。

其他信息:

  1. 据我所知,您可能正在使用using namespace std;,因为您将std::string 声明为string。如果是这种情况,请考虑 using namespace std; 被认为是一种不好的做法(更多信息 here)。

完整代码:

#include <iostream>

int main() {
    std::string name = "george";
    int length = name.size();
    int pNameFirst = 0;
    int pNameLast = length - 1;

    while(pNameFirst < pNameLast)
    {
        std::swap(name[pNameFirst],name[pNameLast]);

        pNameFirst++;
        pNameLast--;
    }
    std::cout << name << std::endl;
}

【讨论】:

  • 这是最准确的版本。谢谢你:)
【解决方案3】:

如果要反转字符串对象,只需执行以下操作(注意这是众多手工方法之一:

#include <iostream>
#include <string>

int main() {

    std::string my_string{"hello"};

    // Similar to your way:
    int index{static_cast<int>(my_string.length() - 1)};
    for (; index >= 0; --index) {
        std::cout << my_string.at(index) << std::endl;
    }
}

【讨论】:

  • 当它不是长度而是索引时最好不要称它为length
  • @largest_prime_is_463035818 是的
  • 由于size_t 是无符号的,你的循环条件是否总是为真,这意味着当index==0 时它会下溢?
  • Stephen Newell 是对的,它正在下溢。 terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::at:: __n (which is 18446744073709551615) &gt;= this-&gt;size() (which is 5).
  • @StephenNewell 这是真的!我会改成正确的循环
猜你喜欢
  • 2013-02-25
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-22
  • 2020-02-07
相关资源
最近更新 更多