Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,943 questions

51,884 answers

573 users

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
...