c++ string class, how to edit a character from within the string?
Hi, in c++, iv got:
string s = "abcdef";
and I want to change 'c' to an 'i'.
How would I do that?
Thanks
Same thing as Fruny posted, just thrown in a loop.
string s = "abcdef";for(int x = 0; x < s.length(); x++){ if(s[x] == 'c') s[x] == 'i';}
Quote:Original post by kmccusker
s[x] == 'i';
One two many equal signs there, just an FYI.
std::size_t i = s.find( 'c' );
if( std::string::npos != i ) {
s = 'i';<br>}<br><br><br>// ville<br>
if( std::string::npos != i ) {
s = 'i';<br>}<br><br><br>// ville<br>
template< class T>class replace{ public: replace(const T& in, const T& out):_in(in),_out(out){} T operator()(const T & in) { if(in == _in) { in = _out; } return in; } private: T _in,_out;};void c_to_i(){ std::string s = "abcdef"; replace<char> replace_func('c','i'); std::transform(s.begin(),s.end(),s.begin(),replace_func);}
but seriously, s[2] = i;
Why is everyone writing their own form of replace? If you want to replace a letter at a known position then use Fruny's code. If you want to replace the first occurance of a specific letter then use ville's code. If you want to replace all occurances of a specific letter then use:
std::replace(string.begin(), string.end(), oldLetter, newLetter);
Enigma
std::replace(string.begin(), string.end(), oldLetter, newLetter);
Enigma
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement