edwardk091997
asked on
How do you do character string replacement?
Hello,
What is the easiest way to do string replacement?
For instance if I want to replace all occurances of the word "old" with the word "new" in the following string = "the old brown fox is very old"
In PERL is would be something like: $var =~ s/old/new/g;
What is the easiest way to do string replacement?
For instance if I want to replace all occurances of the word "old" with the word "new" in the following string = "the old brown fox is very old"
In PERL is would be something like: $var =~ s/old/new/g;
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Note that strcpy isn't used for the actual replacement, since it will take along the trailing null byte. This would prematurely end the target string.
This will only work if the string lengths of "old" and "new" are the same. In this case it is (3). but this is not a general solution. for a generic solution you must copy to another larger buffer.
try:-
#include <stdio.h>
#include <string.h>
void main()
{
char string[] = "the old brown fox is very old";
char output[256];
int count1= 0,count2 = 0;
while (count1 < strlen(string))
if (!strncmp(&string[count1], "old", strlen("old")))
{
strcpy(&output[count2], "new");
count1+=strlen("new");
count2+=strlen("new");
}
else
output[count2++] = string[count1++];
}
you could get rid on the repeated use of strlen to increase efficency.
try:-
#include <stdio.h>
#include <string.h>
void main()
{
char string[] = "the old brown fox is very old";
char output[256];
int count1= 0,count2 = 0;
while (count1 < strlen(string))
if (!strncmp(&string[count1],
{
strcpy(&output[count2], "new");
count1+=strlen("new");
count2+=strlen("new");
}
else
output[count2++] = string[count1++];
}
you could get rid on the repeated use of strlen to increase efficency.
ASKER
the comment from arunm was a better solution....the strings can be different in size...