3

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
  • 1
    Oh my good i feel so stupid. Of course the first element in an array is at index 0. First i tried to change c[3] to 'B' and got complete nonsense, and c[1] is already 'B', thanks for enlighting me. Commented Feb 20, 2015 at 20:52

4 Answers 4

7

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 :)

Sign up to request clarification or add additional context in comments.

Comments

4

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;

}

1 Comment

Yes, but it finds the character and copies the string, neither of which the question asked for...
2

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

c[0] = 'B';

Comments

2

try

c[0] = 'B';

arrays start at 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.