TIP: Click on subject to list as thread! ANSI
echo: aust_c_here
to: All
from: Neville Varghese
date: 1995-09-04 22:25:00
subject: Search & Replace string

Hello All!

Ive only been into C for a few months now, and I'm quite enjoying it. I
cant seem to get the hang of pointers though, but anyway here's my
question. Ive been making a program for Maximus BBS software to edit a
certain binary file. Now, I need a function to do a search and replace on a
string. Sorry I dont have a great deal of commenting on this code here, coz
im a bit confused about it all myself at the moment 8) . Basically
"str" is the string to search for the string to replace.
"search_str" is the string to search for in "str" to be
replaced. "replace_str" is the replacement string for
"search_str" in "str". For example, if "Hello hows
things?" was passed to "str", "things" was passed
to "search_str", and "Mary" was passed to
"replace_str", the string return would be "Hello hows
Mary?" . Here is the code:



char *searchstr(char *str, char *search_str, char *replace_str) {
char *pdest=0;
int str_len=0;
int str_1len=0; //length of str from pos 0 to substring
int str_2len=0; //length of str from substring to end of str int search_str_len=0;
int str_plus_search_len=0;
char str2[113]="";

    pdest = strstr(str, search_str);
       if (pdest==NULL){  // if search string not found in main
       	return str;    // string then return the main string
  }

str_len = strlen(str); //finds length of str
search_str_len = strlen(search_str); //finds length of string to search


str_1len = pdest - str;

str_plus_search_len = str_1len + search_str_len;
str_2len = str_len - (str_1len + search_str_len);

strncpy(str2, str, str_1len);
strcat(str2, replace_str);
strncat(str2, str+str_plus_search_len ,str_2len);
str2[strlen(str2)]='\0';

return str2;

}



Nev.

--- Maximus/2 3.00

* Origin: **Sawasdi BBS** sawasdi.apana.org.au 61 8 2617802 (3:800/846)
SEEN-BY: 50/99 620/243 623/630 711/401 409 410 430 510 807 808 809 932 934
SEEN-BY: 712/515 713/888 714/906 800/1 2 424 441 805 806 809 810 812 814 822
SEEN-BY: 800/831 841 843 846 849 7877/2809
@PATH: 800/846 1 711/808 809 934

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.