【发布时间】:2013-05-13 07:58:56
【问题描述】:
这是一个简单的示例程序:
#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 s1 更改为return "asdf",它将返回asdf。如何使用此函数返回字符串?
【问题讨论】:
-
你实际上并没有初始化你的字符串变量。
-
为什么觉得返回字符串有问题?检查函数内部字符串的值。
-
您输出的文本只是给编译器的文本——它不会试图弄清楚该文本的含义,也不会为您兑现您的承诺。毕竟,也许你是想对用户撒谎。
-
所以我猜你会因为犯了一个愚蠢的错误而被否决?哦,好吧。
-
@fredsbend - 反对票主要意味着这不是一个有趣的问题。对于想要赢得一些声誉的新手来说,这并不好玩,但大多数新手问题甚至对大多数其他新手来说都不感兴趣 - 他们会犯自己的错误,如果他们犯了错误,他们将无法找到你的问题反正同样的错误。通常的术语是“过于本地化”。你得到了帮助 - 不要太担心高分表。
标签: c++ string return-value