How to replace a part of string by another string in C

2 Answers

0 votes
#include <stdio.h>
#include <string.h>

char *str_replace(char *s, char *part, char *replace) {
  static char tmp[1024];
  static char new_s[1024];
  char *p;

  strcpy(tmp, s);

  if (!(p = strstr(tmp, part)))  
    return tmp;

  strncpy(new_s, tmp, p - tmp); 
  new_s[p-tmp] = '\0';

  sprintf(new_s + (p - tmp), "%s%s", replace, p + strlen(part));
  sprintf(s, "%s", new_s);    

  return s;
}

int main(int argc, char **argv) 
{ 
    char s[16] = "index.php";
	
	str_replace(s, "php", "c");
	
	puts(s);
	
	return 0;
}
    
/*
   
run:
    
index.c
 
*/

 

 



answered Jan 22, 2019 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

#define SIZE 1024

void str_replace(char *s, const char *oldStr, const char *newStr) {
    char *pos, tmp[SIZE];
    int index = 0, len = strlen(oldStr);
    
	while ((pos = strstr(s, oldStr)) != NULL) {
        strcpy(tmp, s);
        index = pos - s;
        s[index] = '\0';
        strcat(s, newStr);
        strcat(s, tmp + index + len);
    }
}

int main(int argc, char **argv) 
{ 
    char s[16] = "index.php";
     
    str_replace(s, "php", "c");
     
    puts(s);
     
    return 0;
}

  
/*
   
run:

index.c

*/

 

 



answered Jan 22, 2019 by avibootz
...