替换字符串C的单个字符元素 [英] Replace individual character element of a string C

查看:301
本文介绍了替换字符串C的单个字符元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一些真正基本的C,但我一直得到分段的错误。所有我想做的是用不同的字母替换一个单词的字母 - 在本例中用l替换l。任何人都可以帮助解释我错了什么?这应该是一个真正基本的问题,我想,我只是不知道为什么它不工作。

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;
}

对于我的输出,我得到


string1 hello

string1 [2] l

分段错误

string1 hello
string1[2] l
Segmentation fault

谢谢!

推荐答案


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


无法更改字符串字面值,它是未定义的行为。尝试此操作:

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

char string1[] = "hello";

或也许:

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

/* Stuff. */

free(string1);

这篇关于替换字符串C的单个字符元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆