0

I'm trying to replace a specific character in a string with a different character. I've tried doing the strchr method like other posts have suggested but I'm only getting a segfault.

  char *str = "hello!\n";

  char *ptr;
  if((ptr = strchr(str, '\n')) != NULL) {
    *ptr = '\0';
  }
  • 3
    You may not change a string literal. – Vlad from Moscow May 04 '21 at 19:00
  • 1
    Change to `char str[] = "hello!\n";` – Eugene Sh. May 04 '21 at 19:02
  • Please elaborate "the strchr method". I do not see how a search function can do a replacement for you. I suspect that somebody mislead you there. Please describe the concept and show a [mre] of how you tried to implement it, because frankly the code you show contains a call to strchr but does not exhibit any attribute of an attempt to replace, asssuming that the termination before trailing white space is not what you mean. Without that info, your questions lacks as much detail as "Please write a string replacement for me." – Yunnosch May 04 '21 at 19:03
  • Change the variable to `char str[] = “hello\n”;` so you can modify the string value. – Jonathan Leffler May 04 '21 at 19:03
  • @EugeneSh. can you explain the reason, or logic behind it, why the pointer notation doesn't allow mutable string? but when we change it to square brackets, it is then mutable? – Daniyal Shaikh May 04 '21 at 19:06
  • 1
    The linked duplicate has the explanation – Eugene Sh. May 04 '21 at 19:07

1 Answers1

0

Use this function.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>



void replace_leter(char*,char,char);

int main()
{
char frase[10]="hellow\n";
replace_leter(frase,'\n','\0');
}

void replace_leter(char string_1[],char a,char b)
{
    int i;
    for(i=0;i<strlen(string_1);i++)
    {
        if(string_1[i]==a)
        {
            string_1[i]=b;
            break;
        }
    }
}
julianix
  • 79
  • 7