反转字符串 - c ++

时间:2013-11-27 06:08:19

标签: c++

我正在研究我的C ++,并在逆转用户输入的字符串时进行练习。以下是我的尝试不起作用。

关于为什么的任何想法?

string userentry;
cout << "enter a string: ";

getline(cin, userentry);

int size = userentry.length();

for (int i = 0; i < size /2; i++)
{
    string tempvar1 = userentry.substr(i);

    string tempvar2 = userentry.substr(size - 1 - i);

    userentry.replace(i, i+1, tempvar2);

    userentry.replace(size - 1 -i, (size - 1 - i) + 1, tempvar1);
}

cout << userentry << endl;

return 0;

我感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

基本上,你正在插入一个不断增长的字符串,覆盖越来越多的字符。我认为你打算一次更换一个角色。

尝试将replace()的length参数设置为1,并仅指定临时变量的第一个字符。例如:

for (int i = 0; i < size /2; i++)
{
    string tempvar1 = userentry.substr(i);
    string tempvar2 = userentry.substr(size - 1 - i);
    userentry.replace(i, 1, tempvar2.substr(0, 1));
    userentry.replace(size - 1 -i, 1, tempvar1.substr(0, 1));
}

以下是显示您不断增长的字符串插入的结果:

enter a string: abcdef

Step 1
t1: abcdef
t2: f
ue: abcdef
first replace at 0, length 1 on data: abcdef, using: f
second replace at 5, length 6 on data: fbcdef, using: abcdef

Step 2
t1: bcdeabcdef
t2: eabcdef
ue: fbcdeabcdef
first replace at 1, length 2 on data: fbcdeabcdef, using: eabcdef
second replace at 4, length 5 on data: feabcdefcdeabcdef, using: bcdeabcdef

Step 3
t1: abbcdeabcdefdeabcdef
t2: bbcdeabcdefdeabcdef
ue: feabbcdeabcdefdeabcdef
first replace at 2, length 3 on data: feabbcdeabcdefdeabcdef, using: bbcdeabcdefdeabcdef
second replace at 3, length 4 on data: febbcdeabcdefdeabcdefbbcdeabcdefdeabcdef, using: abbcdeabcdefdeabcdef

results: febabbcdeabcdefdeabcdefabcdefdeabcdefbbcdeabcdefdeabcdef

答案 1 :(得分:-1)

好吧,我不确定你的那个人应该如何工作,但我已经做了一个。

string userentry;
cout << "enter a string: ";

getline(cin, userentry);

int size = userentry.length();

string temp = "";//construscts a temporary string
for (int i = size-1; i >=0; i--){//we want to start at the end of the inputted string because that will be placed at the beggining of the temporary string
    temp.push_back(userentry[i]);//adds the last character to userentry
}
userentry = temp;//assign userentry to its reversed value

cout << userentry << endl;

return 0;