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 start from specific index (position) in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
 
 char *str_replace(char *s, char *part, char *replace, int start) {
  static char tmp[1024];
  static char new_s[1024];
  char *p;
 
  strcpy(tmp, s + start);
 
  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 + start, "%s", new_s);    
 
  return s;
}
 
int main(int argc, char **argv) 
{ 
    char s1[32] = "php.index.php";
    char s2[32] = "php.index.php";
     
    str_replace(s1, "php", "c", 0);
    puts(s1);
     
    str_replace(s2, "php", "c", 5);
    puts(s2);

    return 0;
}
     
/*
    
run:
     
c.index.php
php.index.c
  
*/

 



answered Jan 24, 2019 by avibootz

Related questions

...