How to add characters to a string in the C programming language?

There are several ways in C language to add characters to a string.

  1. Concatenate two strings.
  2. concatenate two strings
#include <string.h>

char str1[20] = "Hello";
char str2[] = " World!";
strcat(str1, str2);   // 将str2追加到str1的末尾
  1. By using pointer operations: you can access each character of a string and insert new characters when necessary.
char str[20] = "Hello World!";
int index = 5;
char newChar = ',';

// 在索引位置插入新字符
int length = strlen(str);
for (int i = length; i >= index; i--) {
    str[i + 1] = str[i];
}
str[index] = newChar;
  1. Inserting new characters directly at an index position using index operations on a character array.
char str[20] = "Hello World!";
int index = 5;
char newChar = ',';

// 在索引位置插入新字符
int length = strlen(str);
for (int i = length; i >= index; i--) {
    str[i + 1] = str[i];
}
str[index] = newChar;

It is important to make sure that the target character array has enough space to store new characters when performing string operations. Additionally, when using pointer operations, be mindful of the position of the string’s null terminator \0 and ensure it is in the correct place.

bannerAds