我正在尝试修改通过反向传递引用传递的字符串 例如:使用“ 递归”将海豚一词改为nihplod。 我无法在修改其标题的功能中添加更多参数。 我现在的输出是 od ,而不是 dolphin ,我认为它只执行最后两个字母,老实说,我不知道为什么。我应该改变什么?这是我的代码。
void reverse(string &word) {
if (word.length() == 1 || word.length() == 0) {
if (word.length() == 1) {
word = word;
}
else if (word.length() == 0) {
word = "nothing to reverse";
}
}
else {
string temp;
if (temp.length() == 0) {
temp = "";
temp = temp+word.substr(word.length() - 1, 1);
word.pop_back();
if (word.length() == 0) {
word = temp;
}
else if (word.length() == 1) {
//temp = temp + word.substr(word.length() - 1, 1);
temp = temp + word;
word.pop_back();
word = temp;
}
else {
reverse(word);
}
}
else {
temp = temp + word.substr(word.length() - 1, 1);
word.pop_back();
if (word.length() == 0) {
word = temp;
}
else if (word.length() == 1) {
//temp = temp + word.substr(word.length() - 1, 1);
temp = temp + word;
word.pop_back();
word = temp;
}
else {
reverse(temp);
}
}
}
}
答案 0 :(得分:0)
算法是这样的:
reverse
您在这里:
void reverse(string& word)
{
size_t len = word.size();
if (len < 2)
{
return;
}
char first = word[0];
char last = word[len - 1];
string inner;
if (len > 2)
{
inner = word.substr(1, len - 2);
reverse(inner);
}
word = last + inner + first;
}
答案 1 :(得分:0)
实现相同目标的非递归方法可能是:
void reverseString(std::string& input)
{
const size_t inputStringLength = input.size();
for (size_t index = 0; index < inputStringLength/2; ++index)
{
// swap the character at "index" position with the character at "inputStringLength - index - 1" position
input[index] ^= input[inputStringLength - index - 1] ^= input[index] ^= input[inputStringLength - index - 1];
}
}
答案 2 :(得分:0)
void rev_recv(std::string& s, int from, int to) {
if (from >= to) return;
rev_recv(s, from + 1, to - 1);
std::swap(s[from], s[to]);
}
答案 3 :(得分:-1)
void reverse(string &word)
{
string temp = word;
if(temp.length != 0)
{
cout << temp.at(temp.length()-1);
reverse(temp.erase(temp.length()-1));
}
else
cout << "\ndone\n";
}
这将反向打印,并且不会修改传入的原始字符串。
如果要修改原始字符串,只需删除temp
变量。