How to extract specific content from a string in C language?
In C language, you can use the standard library function strncp() to extract specific content.
The prototype of the strncpy() function is as follows:
char *strncpy(char *dest, const char *src, size_t n);
In which, dest is a pointer to the destination string, src is a pointer to the source string, and n is the number of characters to be extracted.
Here is a sample code demonstrating how to use the strncpy() function to extract specified content:
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello, World!";
char dest[10]; // 设置目标字符串的长度为10
// 截取源字符串的前9个字符
strncpy(dest, src, 9);
dest[9] = '\0'; // 手动添加字符串结束符
printf("截取的内容为:%s\n", dest); // 输出:截取的内容为:Hello, Wo
return 0;
}
In the above code, we extract the first 9 characters of the source string “Hello, World!” and store them in the target string dest. Since the target string has a length of 10, we manually add the string terminator \0 at the end of the extracted content to ensure it is correctly output.
Caution should be taken when using the strncpy() function to handle the length of the destination string in order to avoid buffer overflow.