Sign in to follow this  
Felon_pro

Advanced string manipulation

Recommended Posts

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 this post


Link to post
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 this post


Link to post
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 s
Some shtring with sh


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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this