C Replace one character in an char array by another
24,639
Solution 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 :)
Solution 2
Below is a code that ACTUALLY WORKS!
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;
}
Solution 3
C arrays are zero base. The first element of the array is in the zero'th position.
c[0] = 'B';
Solution 4
try
c[0] = 'B';
arrays start at 0
Author by
danielr1996
Updated on October 31, 2021Comments
-
danielr1996 over 2 years
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 isABC ABC
. How can I replace the first character in an String / char array? -
mabraham about 7 yearsYes, but it finds the character and copies the string, neither of which the question asked for...