在C語言中,可以使用strncpy()
函數來截取字符串。strncpy()
函數的原型如下:
char *strncpy(char *dest, const char *src, size_t n);
其中,dest
是目標字符串,src
是源字符串,n
是需要截取的字符個數。例如,下面的代碼演示了如何使用strncpy()
函數來截取字符串:
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "hello, world!";
char dest[6]; // 目標字符串長度為6
strncpy(dest, src, 5); // 截取前5個字符
dest[5] = '\0'; // 手動加上字符串結束符
printf("截取后的字符串為: %s\n", dest);
return 0;
}
上述代碼中,源字符串src
為"hello, world!“,目標字符串dest
的長度為6,通過strncpy()
函數截取源字符串的前5個字符,然后手動添加字符串結束符。最終輸出結果為"hello”。