【问题标题】:Why the function is not returning the string?为什么函数不返回字符串?
【发布时间】:2020-07-06 19:58:34
【问题描述】:
#include<iostream>
#include<string.h>
using namespace std;

string revString(string s,string copy,int i,int j)
{   
    if(i==s.length())
        return copy;//if 'i' reaches to the length of the string it returns the copied value
    else{
        copy[i]=s[j];//copying the string s into copy
        return revString(s,copy,++i,--j);// calling recursively 
    }
}

int main()
{
    string s,copy;
    cout<<"Enter a string without entering spaces\n";   
    cin>>s;
    int i=0,j=s.length()-1;
    cout<<revString(s,copy,i,j);//function for reversing the string
    return 0;
}

这里我尝试使用递归将字符串 's' 复制到字符串 'copy' 中,但该函数没有返回任何内容。

【问题讨论】:

  • 在每次迭代时打印copy,您应该能够弄清楚发生了什么。
  • 字符串在分配给不存在的元素时不会展开。相反,行为是未定义的。
  • std::string rev{s.rbegin(), s.rend()};?
  • revString(s,s,i,j); 应该解决 molbdnilo 报告的问题。
  • 添加if (copy.length() == 0) copy.resize(s.length());

标签: c++ string algorithm recursion reverse


【解决方案1】:

您的方法很好,但假设您有 100 个字符,那么它将迭代 100 次。相反,您可以用字符串的后半部分反转前半部分,甚至不必传递太多参数。

这是我的方法

#include<iostream>
#include<string.h>
using namespace std;

string revString(string s, int i = 0)
{
    if((int)(s.length()  / 2) == i)
        return s;
    else{
        char t;
        t = s[i];
        s[i] = s[s.length() - 1 - i];
        s[s.length() - 1 - i]=t;
        return revString(s, ++i);// calling recursively 
    }
}

int main()
{
    string s;
    cout<<"Enter a string without entering spaces\n";   
    cin>>s;;
    cout<<revString(s);//function for reversing the string
    return 0;
}

【讨论】:

    【解决方案2】:

    因为您没有为copy 变量分配内存,而是尝试为其分配值。我建议您阅读更多关于 C++ string 类中的内存分配的信息。

    只要对您的代码进行最少的改动,您就可以在调用 revString() 函数之前添加以下 sn-p 使其工作:

    copy.resize(s.size());
    

    【讨论】:

    • 嗯,我期待这个答案。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-05-12
    • 2016-01-18
    • 2022-01-04
    • 2017-04-15
    • 1970-01-01
    • 2021-12-03
    • 2016-05-12
    • 2019-10-12
    相关资源
    最近更新 更多