如何在c ++函数中返回字符串?

193*_*286 3 c++ string return-value

这是一个简单的示例程序:

#include <iostream>
#include <string>

using namespace std;

string replaceSubstring(string, string, string);

int main()
{
    string str1, str2, str3;

    cout << "These are the strings: " << endl;
    cout << "str1: \"the dog jumped over the fence\"" << endl;
    cout << "str2: \"the\"" << endl;
    cout << "str3: \"that\"" << endl << endl;
    cout << "This program will search str1 for str2 and replace it with str3\n\n";

    cout << "The new str1: " << replaceSubstring(str1, str2, str3);

    cout << endl << endl;
}

string replaceSubstring(string s1, string s2, string s3)
{
    int index = s1.find(s2, 0);

    s1.replace(index, s2.length(), s3);

    return s1;
}
Run Code Online (Sandbox Code Playgroud)

然而它编译该函数什么都不返回.如果我改变return s1return "asdf"它会返回asdf.如何使用此函数返回字符串?

sya*_*yam 11

你永远不会给你的字符串赋值,main因此它们是空的,因此很明显该函数返回一个空字符串.

更换:

string str1, str2, str3;
Run Code Online (Sandbox Code Playgroud)

有:

string str1 = "the dog jumped over the fence";
string str2 = "the";
string str3 = "that";
Run Code Online (Sandbox Code Playgroud)

此外,您的replaceSubstring功能有几个问题:

int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
Run Code Online (Sandbox Code Playgroud)
  • std::string::find返回a std::string::size_type(aka.size_t)而不是a int.两点不同:size_t是无符号的,它并不一定是大小为同一int根据您的平台(例如,在64位Linux或Windows size_t是无符号的64位,而int签订32位).
  • 如果s2不属于,会发生什么s1?我会告诉你如何解决这个问题.提示:std::string::npos;)