新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

c语言substring怎么截取字符串,c语言substring的用法

发布时间:2023-10-27 23:15:27

c语言substring怎样截取字符串

在 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];

    strncpy(dest, src, 5);
    dest[5] = '';

    printf("截取的子串为:%s
", dest);

    return 0;
}

输出结果为:

截取的子串为:Hello

在上面的示例中,src 字符串为 "Hello, World!"dest 字符串长度为 6,通过 strncpy 函数截取了 src 字符串的前 5 个字符,并将结果赋值给 dest 字符串,最后手动添加了字符串结束符

需要注意的是,strncpy 函数可能不会自动添加字符串结束符 ,因此在截取字符串后,需要手动添加结束符。