Thread: Replacing a part of a string with an other???

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    10

    Question Replacing a part of a string with an other???

    Hey all,

    I have a string1: "This is the string"
    and I want to replace the word "the" with string2: "not a"
    so that string1 becomes "This is not a string"

    i know how to use strstr to find the word i want to replace, but i don't know how to actually replace the word with the other string.

    How do i do this?

    Thanks

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Since "not a" is 5 characters and "the" is 3 characters, you'll need to move everything that follows (" string") forward by 2 characters, ensuring that the string is large enough. Then you can write "not a" where "the" is.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    When you use strstr, and it is successful, it will return a pointer to "the". With this new pointer, and the pointer to the source string you searched, you can subtract the two pointers to derive the length of the first portion of the string to move into a new array.

    Then, you concat your replacement string.

    Then, you index past the position of "the" in your source string and from that point forward, concat the remaining portion of the string to the new string.

    That's telling you how to do it without telling you how to do it.

    Todd
    Mainframe assembler programmer by trade. C coder when I can.

  4. #4
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    Do you like that?

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    char *ReplaceStrInsideString(char *ptrStr, const char *replaceStr, const char *insertStr)
    {
    	if(!ptrStr || !insertStr)
    	{
    		fprintf(stderr,"NULL input strings.\n");
    		return NULL;
    	}
    	else
    	{
    		char *nptr = NULL;
    		if((nptr = strstr(ptrStr, replaceStr)) == NULL)
    		{
    			fprintf(stderr, "Can not find \"%s\" string inside \"%s\ string.\n", replaceStr, ptrStr);
    			return NULL;
    		}
    		else
    		{
    			/* Compute final length. */
    			int nEndLen, nReplaceStartIndex;
    			/* Save the lengths that are needed. */
    			int nInsertLen = strlen(insertStr);
    			int nReplaceLen = strlen(replaceStr);
    			int nInitLen = strlen(ptrStr);
    			/* Final length of the string is known. */
    			int nFinalLen = nInitLen - nReplaceLen + nInsertLen + 1;
    			/* Pointers to strings. */
    			char *nFinalStr = NULL;
    			char *nEndStr = NULL;
    			if((nFinalStr = calloc(nFinalLen, sizeof(char))) == NULL)
    			{
    				fprintf(stderr, "Memory Allocation Error.\n");
    				return NULL;
    			}
    			/* Where is the replace string? */
    			nReplaceStartIndex = nptr - ptrStr;
    			if(nReplaceStartIndex < 0)
    				nReplaceStartIndex = -nReplaceStartIndex;
    			nEndLen = nInitLen - nReplaceStartIndex + nReplaceLen+1;
    			if((nEndStr = calloc(nEndLen, sizeof(char))) == NULL)
    			{
    				fprintf(stderr, "Memory Allocation Error.\n");
    				return NULL;
    			}
    			/* Hold the remaining part. */
    			strcpy(nEndStr, &ptrStr[nReplaceStartIndex+nReplaceLen]);
    			/* Copy characters untill the replace string. */
    			strncpy(nFinalStr, ptrStr, nReplaceStartIndex);
    			/* Copy now the insertStr. */
    			strncpy(&nFinalStr[nReplaceStartIndex], insertStr, nInsertLen);
    			/* Append the final characters. */
    			strcpy(&nFinalStr[nReplaceStartIndex+nInsertLen], nEndStr); 
    			/* Free what is unused. */
    			free(nEndStr);
    			/* Return the str. */
    			return nFinalStr;
    		}
    	}
    }
    
    /* Main. */
    int main(int argc, char *argv[])
    {
    	char *nInitString = "This is the string.";
    	char *nFinalStr = ReplaceStrInsideString(nInitString, "the", "is not");
    	printf("Initial String :\t%s\nString Replaced:\t%s\n\n",nInitString, nFinalStr);
    	printf("Hit enter to continue....");
    	getchar();
    }
    Printed Results:

    Initial String : This is the string.
    String Replaced: This is is not string.

    Hit enter to continue....

    (Well memmove can be usefull here......xmmmmmmmmmmmmm)

  5. #5
    Ex scientia vera
    Join Date
    Sep 2007
    Posts
    477
    Bokarinho:

    How about hitting ENTER a few times while coding?

    Reading commented code without proper whitespace is terrible.

    EDIT:

    Also, your code has a memory leak. nFinalStr never gets freed(Sure, your OS may handle that for you, but bad practice either way).
    Last edited by IceDane; 03-23-2008 at 06:48 PM.

  6. #6
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Code:
    if(nReplaceStartIndex < 0)
    	nReplaceStartIndex = -nReplaceStartIndex;
    this code suppose to do some good?

    also you do not need to allocate and free nEndStr
    You could copy the end of string from the original string

    and because you do not modify it char *ptrStr should be declared as const
    as well as char *nInitString
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  7. #7
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    Sure there is a memory leak as i am not freeing the memory used, OS can handle it properly but ok you are right. Secondly about the comments this is C commenting and it is my way of writing so i dont bother. Thirdly yes you can not use the nEndStr and this can be easily avoided and this is the only thing i agree with. But if you want to put yourself cleverer write down your own code and i will comment it too. What i ve done is to provide the user with an answer so to have a point in C how to do it. You are far better....

    Thank C programmers...

  8. #8
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    What i ve done is to provide the user with an answer so to have a point in C how to do it.
    Giving the learning person bad answer is worse than not giving any answer at all...

    If you are trying to teach bad practices on these forums - you should be aware to get adecvate responses about your mistakes...
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  9. #9
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    Give me your good practice......

    Bad practices.....
    XAXAXAXA!!!!!

  10. #10
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    Bad practice beacause i got a bit more memory for the nEndStr haaa?

    OK, give me a break dude, God of C....

  11. #11
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by pseudonoma View Post
    How do i do this?
    Here's a trip down memory lane:
    http://cboard.cprogramming.com/showthread.php?t=35219
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Please check my C++
    By csonx_p in forum C++ Programming
    Replies: 263
    Last Post: 07-24-2008, 09:20 AM
  2. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  3. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  4. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  5. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2003, 12:03 AM