std:string
-
I want to replace the last character of a string represented by std::string with comma. How can i do so ?? Example: std::string mystring("Hellow World"); I want to replace last character of "Hellow World" i.e 'd' by comma "'"
I wrote this function for this purpose. I hope this helps. inline void Replace(std::string* pstr, const char old_char, char* pnew_char) { if(!pstr->empty()) { int n = 0; while((n = pstr->find(old_char)) != -1) { *pstr = pstr->erase(n, 1); *pstr = pstr->insert(n, pnew_char); } } } Usage: Replace(&mystring, 'd', ','); For the last character only you can take: mystring.erase(mystring.length(), 1); mystring.append(','); Greetings ReX
-
I want to replace the last character of a string represented by std::string with comma. How can i do so ?? Example: std::string mystring("Hellow World"); I want to replace last character of "Hellow World" i.e 'd' by comma "'"
-
Isn't that to be
*(++mystring.rbegin()) = '.';
? -
I wrote this function for this purpose. I hope this helps. inline void Replace(std::string* pstr, const char old_char, char* pnew_char) { if(!pstr->empty()) { int n = 0; while((n = pstr->find(old_char)) != -1) { *pstr = pstr->erase(n, 1); *pstr = pstr->insert(n, pnew_char); } } } Usage: Replace(&mystring, 'd', ','); For the last character only you can take: mystring.erase(mystring.length(), 1); mystring.append(','); Greetings ReX
That's also a way to burn CPU cycles. Another (possibly better) way to do it could be std::replace(string.begin(), string.end(), 'a', 'b'); to replace all instances of 'a' with 'b'.
-
Isn't that to be
*(++mystring.rbegin()) = '.';
? -
nope :) rbegin() returns last member of container, as i understand it :))) nobody is perfect
Then, AFAIK, your understanding is wrong. The doc's I've seen says "The rbegin member function returns a reverse iterator that points just beyond the end of the controlled sequence" and every experience I have with rbegin() says the same.