How can you replace a string in the C programming language?

In C language, the function strncpy() can be used to replace strings. This function allows you to replace a portion of one string with another string.

Here is an example code:

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

int main() {
    char str1[50] = "Hello, World!";
    char str2[] = "C programming";
    int start_index = 7; // 需要替换的起始位置
    int end_index = 12; // 需要替换的结束位置

    // 将str2中的内容替换到str1中指定位置
    strncpy(str1 + start_index, str2, end_index - start_index + 1);
    printf("替换后的字符串: %s\n", str1);
    
    return 0;
}

The result output is:

替换后的字符串: Hello, C programming!

In this example, we will replace the word “World” in the string str1 with “C programming” and then print the result. The strncpy() function takes three parameters: the target string, the source string, and the number of characters to copy. Here, we set the target string as str1 plus the starting position, the source string as str2, and the number of characters to replace. It is important to note that we need to add 1 in order to include the character at the ending position.

It is important to note that if the length of the original string is smaller than the length to be replaced, the target string will not be completely replaced. If the length of the original string is larger than the length to be replaced, the target string will be overwritten by the front part of the original string and the remaining part will not be changed.

bannerAds