Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a string from a C++ function? [closed]

This is a simple sample program:

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

It compiles however the function returns nothing. If I change return s1 to return "asdf" it will return asdf. How can I return a string with this function?

like image 948
1934286 Avatar asked Dec 01 '22 19:12

1934286


1 Answers

You never give any value to your strings in main so they are empty, and thus obviously the function returns an empty string.

Replace:

string str1, str2, str3;

with:

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

Also, you have several problems in your replaceSubstring function:

int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
  • std::string::find returns a std::string::size_type (aka. size_t) not an int. Two differences: size_t is unsigned, and it's not necessarily the same size as an int depending on your platform (eg. on 64 bits Linux or Windows size_t is unsigned 64 bits while int is signed 32 bits).
  • What happens if s2 is not part of s1? I'll leave it up to you to find how to fix that. Hint: std::string::npos ;)
like image 165
syam Avatar answered Dec 07 '22 23:12

syam