-1

I am trying to use strstr to see if a string appears in another string. For example, I have a string like: -path-elonmusk-bin. I want to replace a part of it or -path-elonmusk to a "$". So the updated path would be: $/bin.

I am able to change it to "$" but instead of changing the part, it changes the whole string. Is there a way to maybe split the string so it returns the rest of the path.

Here is my code:

char *home = "-path-elonmusk";
char *path = "-path-elonmusk-bin-asksks";
char *strmatching = strstr(path, home);

if(strmatching == path) {
strcpy(path, "~");
}

1 Answers1

3

Your code invokes undefined behavior, because you may not write into a string literal. You must allocate memory for it, since you can not know how long the inputstring will be.

if (match == path)
{
    size_t i = strlen(home);
    char *newstr = malloc(strlen(path) - i + 2);
    newstr[0] = '~';
    strcpy(&newstr[1], &path[i]);
    return newstr;
}

return NULL;
Devolus
  • 21,661
  • 13
  • 66
  • 113
  • Wouldn't `path = "~";` do? – alex01011 Mar 10 '21 at 21:58
  • As I already said, you may not write to a string literal, and this would only change the first character anyway so you would get `~home/elonmusk...` – Devolus Mar 10 '21 at 22:07
  • You're wrong. You are only changing the pointer to point to something else. – alex01011 Mar 10 '21 at 22:11
  • @alex01011, do you understand what `undefined berhavior`means? https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior – Devolus Mar 10 '21 at 22:17
  • I doubt anything in what a wrote and the link had anything in common. GN – alex01011 Mar 10 '21 at 22:20
  • What is line 6 doing? "strcpy(&newstr[1], &path{i]);" – Gerome Miranda Mar 11 '21 at 00:56
  • It copies the string without the the match to the new string. You don't want the match in the resulting string, right? You should learn to use a debugger and examine what your code is doing. It should be `[i]` not `{i]` I fixed that. – Devolus Mar 11 '21 at 07:40