c++ string class, how to edit a character from within the string?

Started by
5 comments, last by Enigma 18 years, 8 months ago
Hi, in c++, iv got: string s = "abcdef"; and I want to change 'c' to an 'i'. How would I do that? Thanks
Advertisement
s[2] = 'i';
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
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>
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

This topic is closed to new replies.

Advertisement