-   Programming (
-   -   replace a substring with another string in C (

zeppelin 04-14-2004 11:40 AM

replace a substring with another string in C
yes. me again :P and this is yet another question for string manipulation in c.
I've searched this forum, but I didn't find sth helpful unluckily. So there I go:
I have
char *path = "/home/user/a_DIR/abc"

and I want to write a code to replace a_DIR with yet_another_DIR..
so path_new would be
char *path_new = "/home/users/yet_another_DIR/abc"

i tried man string and then man every function mention there. I think i could use a combination of them to make the above.<?> I'm not sure.. if you want you can help
thank you very much

ps. I 've tried some stuff with strstr but wasn't able to do have the wanted result

vinay_s_s 04-14-2004 12:12 PM

well u can cut off the string after a_DIR and paste it to another temp string.
Then delete a_DIR.
then concatenate the new string to the path.
then concatenate the temp to path

itsme86 04-14-2004 01:00 PM


#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", "Miami"));

  return 0;

itsme@dreams:~/C$ ./repstr
Hello, Miami!

zeppelin 04-14-2004 01:35 PM

itsme86, you're the man!
I still don't get very well the arithmetic with pointers you do but it works!! :P

dreams.. good one!

ozmosis 04-22-2007 11:41 AM

Wow, wonderful code...too expressive!!!

dmail 04-22-2007 12:23 PM

Doing this sort of thing in memory and from harddisk are different(in C at least) as you can not safely update a file by doing a replace. So normally another couple of steps are involved, so the process becomes:
Read the file and store in memory
Manipulate the stored version
Write the whole memory version to file overwriting the previous version.

ozmosis 04-22-2007 12:59 PM


dmail 04-22-2007 01:31 PM

Help yes, do for you no.

ozmosis 04-22-2007 01:55 PM

Thanks a lot!!!!

ozmosis 04-23-2007 08:08 AM


nx5000 04-23-2007 08:17 AM

Quick look:


  stringa_sost(char buffer3[1000][1000], char buffer1[256], char buffer2[]);
Remove these char keywords!
And probably the array size [1000][1000] , [256]

ozmosis 04-23-2007 09:27 AM


ozmosis 04-24-2007 01:59 PM


dmail 04-24-2007 03:04 PM

Is this a homework/class assignment? how much knowledge do you have of C?

ozmosis 04-24-2007 03:35 PM


All times are GMT -5. The time now is 01:49 PM.