Public Group

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

## Recommended Posts

hello i want to make a program that replaces all 's' characters in a string with 'sh'. how do i do so? Thnx

##### Share on other sites
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.

##### Share on other sites
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

##### Share on other sites
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.

##### Share on other sites
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.

##### Share on other sites
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++

1. 1
2. 2
3. 3
Rutin
19
4. 4
5. 5
JoeJ
12

• 14
• 22
• 9
• 31
• 17
• ### Forum Statistics

• Total Topics
632617
• Total Posts
3007470
• ### Who's Online (See full list)

There are no registered users currently online

×