字符串中的中间字符没有被反转 - C ++(Reinvent)

时间:2015-10-29 01:08:57

标签: c++ string

尝试制作一个小的字符串反转器,并且在反转具有奇数长度返回的字符串的字符时,只有字符串的第一个和最后一个字符似乎被交换:

#include <iostream>

using namespace std;

int main()
{
    string word;
    cout << "Word: ";
    cin >> word;
    if (word.length() % 2 == 0)
    {
        for (int i = 0; i < (word.length()/2); i++)
        {
            swap(word[i], word[word.length() - i - 1]);
        }
    }
    else
    {
        for (int i = 0; i < (word.length()/2 - 1); i++)
        {
            swap(word[i], word[word.length() - i]);
        }
    }
    cout << word << endl;
}

2 个答案:

答案 0 :(得分:2)

这是一个简单的代码:

#include <iostream>

using namespace std;

int main()
{
    string word;
    cout << "Word: ";
    cin >> word;
    for (int i = 0; i < (word.length()/2); i++)
    {
        swap(word[i], word[word.length() - i - 1]);
    }
    cout << word << endl;
}

你不需要if / else语句。

答案 1 :(得分:2)

您的索引逻辑不正确。看看这个。

swap(word[i], word[word.length() - i]);

循环从i == 0开始,您尝试swap()位置i == 0word.length() - i == word.length() - 0 == word.length()的{​​{1}}字符超出界限,因此未定义的行为。在偶数减去1的情况下,你得到了那个部分。

还要考虑word.length() == 1的情况会发生什么。你检查

i < (word.length() / 2 - 1)

for循环为条件。如果word.length() == 1,则word.length() / 2 == 0,现在从中减去1。这将使(unsigned)整数下溢,该整数定义明确,但为您提供最正值,因此您将遍历所有类型的无效索引。

一般来说,我认为您的案例选择不必要地复杂化。如果使用迭代器会更容易。既然你说这是一个练习,我不会告诉你解决方案,但你可以很容易地在网上找到它。这个问题经常被问到这里。