【问题标题】:How to change character in char array如何更改char数组中的字符
【发布时间】:2015-03-17 20:21:38
【问题描述】:

我的函数获取一个 char 数组作为输入。如果它包含字符e,它将用a 更改它并返回新的字符数组。这是我的代码:

char echanger(char word[]){

    int total = 0;
    int i;
    char final[5];

    for(i=0;i<5;i++){
        if(word[i]=='e'){
            final[i] == 'a';
        }
        else{
            final[i] == word[i];
        }
    }

    return final;
}

我在 main() 函数中这样调用它:

int main(){

    char a[] = "helle";
    printf("new string is: %d \n",echanger(a));

}

它给了我这个输出:

new string is: -48

我在这里缺少什么?

【问题讨论】:

  • 我假设 final[i] == 'a';必须是 final[i] = 'a'; (ASSIGN 不是 EVAL)
  • 你的函数被声明为返回char,但你返回的是一个char数组。
  • 您还试图返回一个局部变量,该变量在函数结束时被销毁。

标签: c arrays char


【解决方案1】:

您的程序有几个错误。假设字符串长度。不允许或写入 nul 终止符。不返回指针。使用==,你的意思是=。试图返回一个局部变量。

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

char *echanger(char *word) {
    int len = strlen(word);
    int i;
    char *final = malloc(len+1);
    for(i=0; i<=len; i++) {         // include terminator
        if(word[i] == 'e')
            final[i] = 'a';
        else
            final[i] = word[i];
    }
    return final;
}

int main(){
    char a[] = "helle";
    char *news;
    news = echanger(a);
    printf("new string is: %s\n", news);
    free(news);                     // was from malloc
    return 0;
}

程序输出:

new string is: halla

【讨论】:

    【解决方案2】:

    您正在使用相等 (==) 运算符而不是赋值 (=) 运算符。将final[i] == 'a' 更改为final[i] = 'a'

    如果我用更改重写函数,那么它将是 -

    char echanger(char word[]){
    
        int total = 0;
        int i;
        char final[5];
    
        for(i=0;i<5;i++){
            if(word[i]=='e'){
                final[i] = 'a';
            }
            else{
                final[i] = word[i];
            }
        }
    
        return final;
    }
    

    希望它会有所帮助。
    非常感谢。

    【讨论】:

    • 是的,这是一个问题。我认为另一个是我用 %d 调用它我认为我应该使用别的东西
    • 哦,当然!在 main 方法中,您可以使用 %s。
    • 这仍然不起作用。您正在返回一个局部变量。返回类型为char,但您返回的是char[5]。我不知道为什么它甚至可以在 C 中编译。
    【解决方案3】:

    为什么不直接修改原始字符串而不是创建一个新字符串?

    void echanger(char word[]){
    
        int i;
        int n = strlen(word);
    
        for(i=0;i<n;i++){
            if(word[i]=='e'){
                word[i] = 'a';
            }
        }
    }
    

    注意: = 是赋值。 == 是比较。

    另外您需要使用printf 中的%s 格式说明符来输出字符串。 %d 将尝试将字符串读取为 int,这会为您提供奇怪的值。

    另外 FWIW char final[5] 不够大,无法容纳 C 字符串 "helle"。记住终止空字符。

    【讨论】:

    • 请注意,我的版本返回 void。你现在应该有类似char a[] = "helle"; echanger(a); printf("%s\n", a);
    • 但我不想让它作废?
    • 然后让它返回char*,并用malloc分配一个新的char数组。这是唯一的方法。但是,如果您随后执行printf("%s\n", echanger(a));,则会发生内存泄漏,因为您无法释放分配的内存echanger。将其设为void 并仅修改参数将是最安全的方法。有关详细信息,请参阅 Weather Vane 的答案。
    猜你喜欢
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    相关资源
    最近更新 更多