Jump to content
  • Advertisement
Sign in to follow this  
johnnyBravo

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

This topic is 4836 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Advertisement
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';
}



Share this post


Link to post
Share on other sites
Guest Anonymous Poster
std::size_t i = s.find( 'c' );

if( std::string::npos != i ) {
s[ i ] = 'i';
}


// ville

Share this post


Link to post
Share on other sites

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;

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!