C++:使用递归反转字符串
C++: Reverse a string using recursion
我正在尝试通过反转来修改通过引用传递它的字符串例如:单词海豚,它只使用递归。我无法在修改其标头的函数中添加更多参数。 我现在的输出是od而不是海豚,我认为它只做最后两个字母,老实说我不知道为什么。有什么我应该改变的吗?这是我的代码。
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);
}
}
}
}
算法是这样的:
- 如果字符串长度小于 2,则返回
- 去除单词的第一个和最后一个字符以创建子字符串 递
- 归调用子字符串上的
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;
}
实现相同目标的非递归方式可以是:
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];
}
}
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]);
}
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 << "ndonen";
}
这将反向打印,而不会修改传入的原始字符串。 如果要修改原始字符串,只需删除temp
变量即可。
相关文章:
- 字符串化递归的"std::vector<std::vector<...>>"而不使用部分模板函数专用化
- 递归形成字符串中所有数字字符的中间和?
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符
- 递归二进制搜索与字符串数组
- 我在 C++ 中创建了一个函数来递归反转字符串,但是之后如何使功能打印一个 endl?
- C++:递归地将字符串中一个字母的所有实例替换为另一个字母
- 如何使用递归打印最长公共子序列中涉及的字符串?
- 十进制到八进制递归C++.以标准::字符串格式输出
- c 字符串 c++ 中 strlen 的递归版本
- 字符串的递归二进制搜索-C++
- 在c++中使用递归从字符串中删除所有辅音
- 使用递归函数 (c++) 将长字符串转换为整数时输出错误
- 如何将从第 2 个字符开始的字符串作为函数中的参数传递以进行递归,并约束数据 tiee 是函数中的字符串?
- 有没有一种递归的方式来制作这个字符串数组?
- 这个简单的 C++ 递归函数来反转字符串有什么问题?
- C 反向字符串递归
- C++ 字符串递归子叉
- 字符串递归函数中的字符串错误
- 基于字符串递归输入Json对象