advanced string manipulation

M

MC felon

hello again..
i want to design a program which takes in a string and replaces all 's'
characters with 'sh'. how do i do it? thanks a lot!
 
I

Ian Collins

MC said:
hello again..
i want to design a program which takes in a string and replaces all 's'
characters with 'sh'. how do i do it? thanks a lot!
What have you tried?
 
M

MC felon

here's what i have tried:

cout<< "enter a string\n\n";

gets(take);

//calculation

int len = 0;

char temp[2];

len = strlen(take);

for(int g=0;g<len;g++)
{
while(take[g] != ' \0 ')
{
if(take[g] == 's')
{
//dont know what to do
}
}
}
cout<< take;
getch();
}
 
I

Ian Collins

MC felon wrote:

In future, please a) quote some context in your reply and b) post
something that compiles on its own.
here's what i have tried:

cout<< "enter a string\n\n";

gets(take);
gets is vile (the root or most buffer overflows), avoid at all cost.
Use std::getline, which takes the maximum buffer size as a parameter.
//calculation

int len = 0;
Introduce len where it is assigned.
char temp[2];

len = strlen(take);

for(int g=0;g<len;g++)
{
while(take[g] != ' \0 ')

You don't want this inner loop, the for is already traversing take. Use
one or the other.
{
if(take[g] == 's')
{
You would be best to declare a second array, double the size of take and
copy the characters to this. Where take[g] == 's', add an 'h'.
//dont know what to do
}
}
}
cout<< take;

Should add << std::endl here.

why?
 
P

peter koch

MC said:
here's what i have tried:

cout<< "enter a string\n\n";

gets(take);

//calculation

int len = 0;

char temp[2];

len = strlen(take);

for(int g=0;g<len;g++)
{
while(take[g] != ' \0 ')
{
if(take[g] == 's')
{
//dont know what to do
}
}
}
cout<< take;
getch();
}

What I see above (disregarding cout) is C code. So you have basically
two choices:

a) switch to the more appropriate std::string and return if you have
problems using that one.
b) Remove the line that couts take and ask at comp.lang.c. That group
will have all the expertise needed to deal with C and can give you a
much better answer.

/Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top