Cover Image for Add a Character to a String in C
135 views

Add a Character to a String in C

The strings in C are represented as arrays of characters. To add a character to the end of a string, you need to find the null-terminator (‘\0’) character that marks the end of the current string and then append the new character after it. Here’s how you can do it:

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

int main() {
    char str[100] = "Hello"; // Existing string
    char newChar = '!';

    // Find the length of the existing string
    int length = strlen(str);

    // Add the new character to the end
    str[length] = newChar;
    str[length + 1] = '\0'; // Add null-terminator after the new character

    printf("Modified string: %s\n", str);

    return 0;
}

In this example, we first find the length of the existing string using strlen. Then, we place the new character in the position after the last character of the existing string and add a null-terminator after it to ensure the string remains properly terminated.

Please note that you need to ensure that the resulting string doesn’t exceed the allocated size of the character array. In this case, the size of the str array is 100 characters, so you should make sure that the combined length of the original string and the new character doesn’t exceed this limit.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS