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 s1
naar return "asdf"
retourneren, wordt het asdf
retourneren. Hoe kan ik een string met deze functie retourneren?
Antwoord 1, Autoriteit 100%
U geeft nooit een waarde aan uw snaren in main
zodat 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 replaceSubstring
functie:
int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
std::string::find
retourneert eenstd::string::size_type
(ook bekend alssize_t
) niet eenint
. Twee verschillen:size_t
is niet ondertekend, en het is niet noodzakelijk dezelfde grootte als eenint
, afhankelijk van uw platform (bijv. op 64 bits Linux of Windowssize_t
is niet-ondertekend 64 bits terwijlint
is ondertekend 32 bits).- Wat gebeurt er als
s2
geen deel uitmaakt vans1
? 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.