Below is the code for find and replace a sub string from a string.But i am not able to pass arguments to the function.
Error Message :
invalid initialization of non-const reference of type ‘std::string& {aka std::basic_string&}’ from an rvalue of type ‘const char*’
please help with explanation
#include <iostream>
#include <string>
using namespace std;
void replaceAll( string &s, const string &search, const string &replace ) {
for( size_t pos = 0; ; pos += replace.length() ) {
pos = s.find( search, pos );
if( pos == string::npos ) break;
s.erase( pos, search.length() );
s.insert( pos, replace );
}
}
int main() {
replaceAll("hellounny","n","k");
return 0;
}
A simplified explanation is that since your replaceAll function is changing a string, you must give it an actual string to change.
int main() {
string str = "hellounny";
replaceAll(str,"n","k");
return 0;
}
This should remove the error:
#include <iostream>
#include <string>
using namespace std;
void replaceAll( string &s, const string &search, const string &replace ) {
for( size_t pos = 0; ; pos += replace.length() ) {
pos = s.find( search, pos );
if( pos == string::npos ) break;
s.erase( pos, search.length() );
s.insert( pos, replace );
}
}
int main() {
string temp = "hellounny";
replaceAll(temp,"n","k");
return 0;
}
If you want to be able to pass temporaries in as a parameter, you could return the result instead:
std::string replaceAll(string s, const string &search, const string &replace ) {
for( size_t pos = 0; ; pos += replace.length() ) {
pos = result.find( search, pos );
if( pos == string::npos ) break;
result.erase( pos, search.length() );
s.insert( pos, replace );
}
return s;
}
std::string result = replaceAll("hellounny", "n", "k");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With