Advanced string manipulation

Started by
4 comments, last by Will F 17 years, 6 months ago
hello i want to make a program that replaces all 's' characters in a string with 'sh'. how do i do so? Thnx
Advertisement
What programming language are you using? What type of variable is the string in? Try to ask questions in a bit more detail. Maybe someone will be able to reply then.
Open file A for input (or use the standard input stream)Open file B for output (or use the standard output stream)While not at the end of file A:  Read a character from A  If it is not an 's':      Write the character to file B  Otherwise:      Write the string "sh" to file B.


Alternatively, if you have the right tools installed, open a command line and type: sed -e s/s/sh/g inputfile outputfile
"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
If you're just doing it to a text file, any good text editor (even notepad!) has search-replace functionality. Search for: s replace with: sh.
___________________________________________________David OlsenIf I've helped you, please vote for PigeonGrape!
I'm reading your question as meaning on a string in a program rather than a file. If I go out on a limb and assume that you are using C++, I'll make a further assumption that you are using std::string. It is easiest to make a temporary copy.

NOTE: There is probably an even better way than this using the standard algorithms. Count to ten and a better way will have been posted.

void ReplaceCharWithString(char C,const std::string &New,std::string &S){    std::string R;    for(std::string::iterator i=S.begin();i!=S.end();++i)        {        if(*i==C) R+=New;        else      R+=*i;        }    S=R;}int main(){    std::string X="shellos";    std::cout << X << "\n";    ReplaceCharWithString('s',"sh",X);    std::cout << X << "\n";    return 0;}// output:// shellos// shhellosh


If you are not using std::string (and if not, why not?) and are using raw char arrays, the same principle can be applied, although you need to bear in mind that a complication is that the finished string will be longer than the original.
I normally don't use boost with posts in the For Beginners forum, but given that the subject of this thread is "Advanced string manipulation", this is an easy way to do it.

#include <boost/algorithm/string.hpp>#include <iostream>#include <string>int main(){	std::string foo("Some string with s");	std::cout << foo << "\n";	boost::algorithm::replace_all(foo, "s", "sh");	std::cout << foo << "\n";}


Which will output
Some string with sSome shtring with sh


Note that "S" and "s" are not the same character, and I am assuming C++

This topic is closed to new replies.

Advertisement