C Replace one character in an char array by another

早过忘川 提交于 2020-01-15 09:56:08

问题


I have the following C Code

#include <stdio.h>
int main(void){
    char c[] = "ABC"
    printf("%s ", c);
    c[1] = 'B';
    printf("%s", c);
    return 0;
}

The output I want is ABC BBC but the output I get is ABC ABC. How can I replace the first character in an String / char array?


回答1:


Indexing in C arrays start from 0. So you have to replace c[1] = 'B' with c[0] = 'B'.

Also, see similar question from today: Smiles in output C++ - I've put a more detailed description there :)




回答2:


below is a code that ACTUALLY WORKS !!!!

Ammar Hourani

char * replace_char(char * input, char find, char replace) 

{

char * output = (char*)malloc(strlen(input));

for (int i = 0; i < strlen(input); i++)
{
    if (input[i] == find) output[i] = replace;
    else output[i] = input[i];
}

output[strlen(input)] = '\0';

return output;

}




回答3:


C arrays are zero base. The first element of the array is in the zero'th position.

c[0] = 'B';



回答4:


try

c[0] = 'B';

arrays start at 0



来源:https://stackoverflow.com/questions/28637882/c-replace-one-character-in-an-char-array-by-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!