Important alert: (current site time 7/15/2013 6:14:03 PM EDT)
 

VB icon

String Replacement (str_replace)

Email
Submitted on: 10/5/2006 1:36:29 AM
By: Brian Folts 
Level: Advanced
User Rating: By 5 Users
Compatibility: C
Views: 27870
(About the author)
 
     This gives you the ability to use str_replace in C. str_replace is a very powerful function with many applications.
 

INCLUDE files:

Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
//**************************************
//INCLUDE files for :String Replacement (str_replace)
//**************************************
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
 
Terms of Agreement:   
By using this code, you agree to the following terms...   
  1. You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
				
//**************************************
// Name: String Replacement (str_replace)
// Description:This gives you the ability to use str_replace in C. str_replace is a very powerful function with many applications.
// By: Brian Folts
//
// Inputs:First parameter is string to replace.
Second parameter is what to replace with.
Third parameter is the string to do it in.
//
// Returns:Returns the new string with all occurences of first parameter replaced with second parameter.
//
//This code is copyrighted and has// limited warranties.Please see http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=10890&lngWId=3//for details.//**************************************

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//replaces all occurences with another occurence
char *str_replace(char * t1, char * t2, char * t6){
	char*t4;
	char*t5=malloc(0);
	while(strstr(t6,t1)){
		t4=strstr(t6,t1);
		strncpy(t5+strlen(t5),t6,t4-t6);
		strcat(t5,t2);
		t4+=strlen(t1);
		t6=t4;
	}
	return strcat(t5,t4);
}
int main(){
	printf("%s",str_replace("hello","goodbye","hello worldhello hello hello helloworld hello hello hello hello hellohello worldhello hello hello helloworld hello hello hello hello hellohello worldhello hello hello helloworld hello hello hello hello hello,and then it gets to the new line?\n"));
	return 0;
}


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Advanced category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

10/6/2006 9:43:37 AMcm

this was really good: basic, usefull...
(If this comment was disrespectful, please report it.)

 
10/6/2006 10:15:27 AMcm

btw. commenting your code is allways important. i was have to twist my brains for a while to understand that function
(If this comment was disrespectful, please report it.)

 
10/6/2006 11:59:41 AMcm

Question: why not using Free(). can u make an example which has free(included). or doesnt it have to be freeŽd in this case?

Email: n0rths1de@hotmail.com
(If this comment was disrespectful, please report it.)

 
10/6/2006 11:59:49 AMcm

Question: why not using Free(). can u make an example which has free(included). or doesnt it have to be freeŽd in this case?

Email: n0rths1de@hotmail.comNOSPAM
(If this comment was disrespectful, please report it.)

 
10/13/2006 12:02:34 AMZaccheus

this is good code for the beginner level category, not advanced.
(If this comment was disrespectful, please report it.)

 
11/28/2006 11:42:16 PMMike C

This is one of those 'bad idea' coding practices. I seriously can't believe this won a superior coding award.

Anyway, for starters malloc(0) returns NULL. Read any documentation, its NULL. So what happens when we strcat to t5 (which is NULL)? We write to undesired locations in memory. We can cause fatal program and system errors doing this. Is this a big deal? YES. HUGE. Do yourself a favor and never use this code.

I want to include more but I cant, 1000 char max.
(If this comment was disrespectful, please report it.)

 
11/28/2006 11:46:16 PMMike C

Improvements: (2of4):

1. Whenever you pass buffers to a function (i.e. the char * pointers in the above str_replace function) always include the size of the buffer as a parameter. Why? Pointers don't store array sizes, they only point to the beginning of a memory block. If I were to assume the length of t1 is strlen(t1) and t1 was created with a buffer length of 5 (char *t1passedtostr_replace = new char[5]) and contained the word "world" then I would have a buffer overrun. Why? strlen requires a NULL terminating character and continues to read until it finds the byte 0. Essentially it will read past the buffer because the fifth element of t1 is 'd' and not 0.

2. Write your own strlen algorithm. Example:
size_t strlen(char *buffer, size_t buffersize) {
size_t i=0;
while(buffer[i] != 0 && i < buffersize)
{ ++i; }
return i;
};
(If this comment was disrespectful, please report it.)

 
11/28/2006 11:47:03 PMMike C

Improvements: (2nd 2 of 4):

3. Return a boolean (fail or succeed) or an int for the number of replacements and send additional parameters for str_replace function for the new text buffer and new buffer length.

4. Check to verify the parameters sent to str_replace are acceptable values. if either t1, t2 or t6 are NULL we should abandon the alg asap.
(If this comment was disrespectful, please report it.)

 
1/1/2007 12:16:53 AMJoe Smith

if there is going to be much string manipulation in the program, its such a pain in the butt to call all these string manipulations, perhaps consider creating your own string class, it might be more time consuming to get up and running, but it will be worth the time. then maybe it might also be intermediate level
(If this comment was disrespectful, please report it.)

 
6/4/2008 6:19:22 AMAndrew

This code does NOT work. It's unreliable and completely unpredictable. It affects random memory addresses and overwrites anything important that might be there. If the bug doesn't show itself right away, it is almost untraceable later in the project.

Do not use this function.
(If this comment was disrespectful, please report it.)

 
1/7/2010 8:18:09 AMIan

This code looks neat but doesn't work, I tried compiling and running in both Unix and Visual Studio. I have found some code that does work: http://refactormycode.com/codes/930-str_replace
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.