Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

str_replace in C ?

Status
Not open for further replies.

schoeppchen

IS-IT--Management
Aug 25, 2005
3
DE
Hi there,

I have to write a short function for search and replacing a string in native C and I wonder if C has such a function build-in??

Thanks in advance,
schoeppchen
 
Hi:

I've had this in my library forever. You might not like the occurrence flag:

Regards,

Ed

#include <stdio.h>

void replace();

void main()
{
char *str = &quot;,a string, of tokens,&quot;;
printf(&quot;%s\n&quot;, str);
replace(str, '&', ',', 0);
printf(&quot;%s\n&quot;, str);
}

/*
* This function replaces old_char with new_char in string.
* If the convert flag is 0 replace all occurrences of old char.
* If the flag > 0, only replace that occurrence of the character
*/
void replace(string, new_char, old_char, convert_flag)
char *string;
char new_char;
char old_char;
int convert_flag;
{
int c_flag=0;

while(*string)
{
if(*string == old_char)
c_flag++;

if(convert_flag == 0 || convert_flag == c_flag)
if(*string == old_char)
{
*string = new_char;
if(convert_flag > 0)
break;
}
string++;
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top