Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace individual character element of a string C [duplicate]

I am trying to do something really basic on C but I keep getting a segmentation fault. All I want to do is replace a letter of a word with a different letter- in this example replace the l with a L. Can anyone help explain where I have gone wrong? It should be a really basic problem I think, I just have no idea why its not working.

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

int main(int argc, char *argv[])
{
    char *string1;

    string1 = "hello";
    printf("string1 %s\n", string1);    

    printf("string1[2] %c\n", string1[2]);
    string1[2] = 'L';
    printf("string1 %s\n", string1);

    return 0;
}

For my output I get

string1 hello
string1[2] l
Segmentation fault

Thanks!

like image 681
user1163974 Avatar asked Feb 05 '12 12:02

user1163974


People also ask

Can I replace a character in a string in C?

Master C and Embedded C Programming- Learn as you goEnter a string at run time and read a character to replace at console. Then, finally read a new character that has to be placed in place of an old character where ever it occurs inside the string.

How do I replace a character in a string in Java?

String are immutable in Java. You can't change them. You need to create a new string with the character replaced.


1 Answers

string1 = "hello";
string1[2] = 'L';

You can't change string literals, it's undefined behavior. Try this:

char string1[] = "hello";

Or maybe:

char *string1;
string1 = malloc(6); /* hello + 0-terminator */
strcpy(string1, "hello");

/* Stuff. */

free(string1);
like image 161
cnicutar Avatar answered Sep 28 '22 07:09

cnicutar