• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 251
  • Last Modified:

How do you do character string replacement?


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;
  • 2
1 Solution
The best thing to use for that is the function strstr. It is not as powerful as perls solution obviously, but it will do.

char *strstr(char *string1, char *string2)

will find the first occurrence of string2 in string1. So a loop of

int i;
char *p;

{   for(i=0; i<strlen(new); ++i)p[i]=new[i];

should do what you need.

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.


#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");
                  output[count2++] = string[count1++];


you could get rid on the repeated use of strlen to increase efficency.

edwardk091997Author Commented:
the comment from  arunm was a better solution....the strings can be different in size...
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now