5

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

#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;
}

它编译但是该函数不返回任何内容。如果我更改return s1return "asdf"它将返回asdf。如何使用此函数返回字符串?

4

3 回答 3

12

您永远不会为您的字符串赋予任何值,main因此它们是空的,因此显然该函数返回一个空字符串。

代替:

string str1, str2, str3;

和:

string str1 = "the dog jumped over the fence";
string str2 = "the";
string str3 = "that";

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

int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
  • std::string::find返回 a std::string::size_type(aka. size_t) 而不是int. 两个区别:size_t是无符号的,并且它不一定与int取决于您的平台的大小相同(例如,在 64 位 Linux 或 Windowssize_t上是无符号的 64 位,int而是有符号的 32 位)。
  • 如果s2不属于会发生什么s1?我会把它留给你来找到解决这个问题的方法。提示:std::string::npos;)
于 2013-05-18T05:39:50.347 回答
4
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;

由此,我看到您尚未初始化 str1、str2 或 str3 以包含您正在打印的值。我可能建议先这样做:

string str1 = "the dog jumped over the fence", 
       str2 = "the",
       str3 = "that";

cout << "These are the strings: " << endl;
cout << "str1: \"" << str1 << "\"" << endl;
cout << "str2: \"" << str2 << "\"" << endl;
cout << "str3: \"" << str3 << "\"" << endl << endl;
于 2013-05-18T05:40:57.210 回答
2

为您的字符串分配一些东西。这肯定会有所帮助。

于 2013-05-18T05:39:36.913 回答