Hoe een string retourneren van een C++ -functie?

Dit is een eenvoudig voorbeeldprogramma:

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

Het compileert, maar de functie retourneert niets. Als ik return s1naar return "asdf"retourneren, wordt het asdfretourneren. Hoe kan ik een string met deze functie retourneren?


Antwoord 1, Autoriteit 100%

U geeft nooit een waarde aan uw snaren in mainzodat ze leeg zijn, en dus retourneert de functie een lege tekenreeks.

Vervangen:

string str1, str2, str3;

Met:

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

U hebt ook verschillende problemen in uw replaceSubstringfunctie:

int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
  • std::string::findretourneert een std::string::size_type(ook bekend als size_t) niet een int. Twee verschillen: size_tis niet ondertekend, en het is niet noodzakelijk dezelfde grootte als een int, afhankelijk van uw platform (bijv. op 64 bits Linux of Windows size_tis niet-ondertekend 64 bits terwijl intis ondertekend 32 bits).
  • Wat gebeurt er als s2geen deel uitmaakt van s1? Ik laat het aan jou over om uit te zoeken hoe je dat kunt oplossen. Hint: std::string::npos😉

Antwoord 2, autoriteit 33%

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;

Hieruit zie ik dat je str1, str2 of str3 niet hebt geïnitialiseerd om de waarden te bevatten die je afdrukt. Ik zou kunnen voorstellen om dit eerst te doen:

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;

Antwoord 3, autoriteit 17%

Wijs iets toe aan uw strings. Dit zal zeker helpen.

Other episodes