Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

replacing a white space with a plus sign in a string

Status
Not open for further replies.

j420exe

MIS
Feb 17, 2002
28
US
New to C: I have a string that is 35 characters long excluding the ():
(New City )
I would like to create a new string that looks like this:
(New+City+++++++++++++++++++++++++++)
How can I go about this?
 
the straight forward approach is this

Code:
void replaceSpaces(char* buffer,char replaceChar)
{
   for(int i = 0;i<strlen(buffer);i++)
   {
     if(buffer[i] == ' ')
            buffer[i]=replaceChar;
   }
}

Matt
 
int i;
char buffer[] = &quot;abc def&quot;;
char replaceChar[] = &quot;+&quot;;

for(int i = 0;i<strlen(buffer);i++)
{
if(buffer == ' ')
buffer = replaceChar;
}

I am receiving an error when this line
buffer = replaceChar; is being executed. Is this line going to build the new string?




 
Well, since you declare replaceChar as a string you cannot do:
buffer = replaceChar;

This would mean that you want to assign a pointer address to a character...I think what you want to do is this:
int i;
char buffer[] = &quot;abc def&quot;;
char replaceChar = '+';

for (i = 0; i < strlen(buffer); i++) {
if(buffer == ' ') {
buffer = replaceChar;
}
}

Note the difference between writing &quot;+&quot; and '+'. The first means &quot;the address of a string containing a plus and then a null-character&quot; and the second means &quot;a plus-character&quot;. There is a seemingly subtle, but crucial difference.

Happy hacking =)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top