如何从C++函数返回一个字符串?

7
这是一个简单的示例程序:
#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。如何在该函数中返回一个字符串?


9
你实际上没有初始化你的字符串变量。 - Cairnarvon
你认为为什么返回字符串存在问题?检查函数内部字符串的值。 - juanchopanza
你输出的文本只是编译器看到的文字,它不会试图理解这些文字的含义,也不会替你兑现承诺。毕竟,也许你本来就想欺骗用户。 - user180247
1
所以我猜你因为犯了一个愚蠢的错误而被投下反对票?哦,好吧。 - user1934286
2
@fredsbend - 通常,被踩经常意味着这不是一个有趣的问题。对于想要赚取一些声望的新手来说,这并不好玩,但大多数新手问题甚至对其他新手来说也不是很有趣——他们会犯自己的错误,如果他们犯了同样的错误也找不到你的问题。通常的术语是“过于局部化”。你得到了帮助——不必太担心高分表。 - user180247
3个回答

13
你在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 返回的是 std::string::size_type 类型(也就是size_t),而不是 int。两者之间的不同: size_t 是无符号的,并且它在不同平台上的大小可能与 int 不同(例如,在64位的Linux或Windows操作系统中,size_t 是无符号的64位,而 int 是有符号的32位)。
  • 如果 s2 不是 s1 的一部分会发生什么?我将让你去找如何解决这个问题。提示:使用 std::string::npos ;)

1
是的。现在已经很晚了。这是个愚蠢的错误。谢谢。 - user1934286
@fredsbend:我刚刚添加了另一个问题(与您的问题无关),请查看我的编辑。 - syam
我已经使用while循环解决了第二个问题,如果index大于s1.length()则退出循环。这样的效果是它现在替换了所有s2的实例为s3。虽然我曾经遇到过size_t,但我对它不太熟悉。 - user1934286
1
@fredsbend:只需要一个if,不需要使用while。至于size_t,重要的是你要习惯它。 :) 为了避免这种情况发生,我最好的建议是在使用每个API之前系统地验证文档,直到你对其感到舒适为止。cppreference是一个很好的地方。我知道这很繁琐,但这是学习和编写优秀代码的最佳方式。 - syam

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;

3

将某些东西分配给您的字符串。这肯定会有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接