plz help me understand this code......

1 reply [Last post]
amanhoney
Offline
Last seen: 10 years 11 weeks ago
Joined: 2010-01-08
bOt Points: 70

/* Replace a sub-string in a string */ /* REPLACE.C*/

# include<stdio.h>
# include<string.h>
int index_str1,index_str2,k;
int c[100];
int str_rep(char *, char *, int *);
/* Function str that finds first location of the sub-string */
int str_rep(char *s1, char *s2, int c[]) {
int count = 0;
int l =0; int j, i = 0;
char s3[]= "Jaunpur";
for(index_str1 = 0; s1[index_str1]; index_str1++)
for(index_str2=index_str1, k = 0; s1[index_str2] == s2[k]&&s1[index_str1]; index_str2++, k++)
if(!s2[k+1])
{
count ++; c[l++] = index_str1;
for(j = index_str1; j < strlen(s3)+index_str1; j++)
s1[j] = s3[i++];
printf("\n %s ", s1);
}
return(count);
}
/* Function main */
int main() {
char *s;
int c[100];
char s1[]="Ram Bahadur Bahadur Patel";
char s2[] ="Bahadur";
int count;
str_rep(s1, s2,c);
return (0);
}

shashwat
Offline
Last seen: 1 year 31 weeks ago
Joined: 2009-02-18
bOt Points: 1160
Replace a sub-string in a string

Check out the program below -

#include <stdio.h>

#include <string.h>


char *replace_str(char *str, char *orig, char *rep)

{

  static char buffer[4096];

  char *p;


  if(!(p = strstr(str, orig)))  // Is 'orig' even in 'str'?

    return str;


  strncpy(buffer, str, p-str); // Copy characters from 'str' start to 'orig' st$

  buffer[p-str] = '\0';


  sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig));


  return buffer;

}


int main(void)

{

  puts(replace_str("Hello, world!", "world", "Delhi"));


  return 0;

Founder and Admin