在在C字符串数组变化特征 [英] Change characters in a string array in C

查看:133
本文介绍了在在C字符串数组变化特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图改变A字符转换为E,在一个字符串数组。但是我收到一个错误 * POS ='E'; 行。它说:MAIN.EXE已停止工作。我不明白的问题。你有什么想法?

  INT主要(无效){
    字符* sehirler [] = {伊斯坦布尔,安卡拉,伊兹密尔,\\ 0};
    INT I;
    对于(i = 0; * sehirler [I] ='\\ 0';!++我){
        字符* POS = sehirler [I]
        而(* POS!='\\ 0'){
            如果(* POS =='A'){
                的printf(%C,* POS);
                * POS ='E'; // ERRROR
            }
            POS ++;
        }
    }
    返回0;
}


解决方案

你的是不是一个字符串数组,它是指向字符串数组,你不能改变字符串。

要使它成为一个数组试试这个

  INT主(INT ARGC,CHAR * ARGB [])
{
    炭sehirler [4] [9] = {伊斯坦布尔,安卡拉,密尔,};
    / * ^^
     * | | __在伊斯坦布尔`字符数'+'\\ 0'
     * | _数组中的字符串数
     * /
    INT I;
    对于(i = 0; * sehirler [I] ='\\ 0';!++我)
    {
        字符* POS = sehirler [I]
        而(* POS!='\\ 0')
        {
            如果(* POS =='A')
            {
                的printf(%C,* POS);
                * POS ='E'; // ERRROR
            }
            POS ++;
        }
    }
    返回0;
}

您可能需要与分配空间的malloc(),然后用的strcpy()制作的副本字面值,那么副本将是修改的。

I try to change 'a' characters into 'e', in a string array. But I receive an error *pos = 'e'; line. It says "Main.exe has stopped working". I could not understand the problem. Do you have any idea?

int main(void) {
    char *sehirler[] = { "Istanbul", "Ankara", "Izmir", "\0" };
    int i;
    for (i = 0; *sehirler[i] != '\0'; ++i) {
        char *pos = sehirler[i];
        while (*pos != '\0') {
            if (*pos == 'a') {
                printf("%c", *pos);
                *pos = 'e';          //ERRROR
            }
            pos++;
        }
    }
    return 0;
}

解决方案

Yours is not a string array, it's an array of pointers to string literals, and you can't change string literals.

To make it an array try this

int main(int argc, char *argb[])
{
    char sehirler[4][9] = {"Istanbul", "Ankara", "Izmir", ""};
    /*            ^  ^
     *            |  |__ Number of characters in `Istanbul' + '\0'
     *            |_ Number of strings in the array
     */
    int   i;
    for (i = 0 ; *sehirler[i] != '\0' ; ++i)
    {
        char *pos = sehirler[i];
        while (*pos != '\0')
        {
            if (*pos == 'a')
            {
                printf("%c", *pos);
                *pos = 'e';          //ERRROR
            }
            pos++;
        }
    }
    return 0;
}

you might need to allocate space with malloc() and then use strcpy() to make a copy of the literals, then the copy will be modifiable.

这篇关于在在C字符串数组变化特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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