如何在 C 语言中获取子字符串
本教程介绍了如何在 C 语言中从字符串中获取子字符串,从字符中获取子字符串的方法有 memcpy()
和 strncpy()
等。
memcpy()
函数在 C 语言中获取子字符串
memcpy()
函数将源文件中的字符数复制到目标文件的内存区。这个函数在 <string.h>
头文件中可用。
当源地址和目标地址重叠时,这个函数会产生问题。这个函数不检查地址是否为空,也不检查是否发生溢出。
memcpy()
函数返回一个指向目标字符串的指针。没有返回值来显示错误。
memcpy()
的语法
void *memcpy(void *destination_string, const void *source_string, size_t number);
-
destination_string
是指向目标字符串的指针。 -
source_string
是指向原始字符类型值数组的指针。 -
number
是字符数。
#include <stdio.h>#include <string.h> int main(void)
{
char *text = "The test string is here";
char subtext[7];
memcpy(subtext,&text[9],6);
subtext[6] = '\0';
printf("The original string is: %s\n",text);
printf("Substring is: %s",subtext);
return 0;
}
输出:
The original string is: The test string is here
Substring is: string
strncpy()
函数在 C 语言中获取子字符串
strncpy()
函数与 strcpy()
函数相同。唯一不同的是,strncpy()
函数将给定数量的字符从源字符串复制到目标字符串。strncpy()
函数在 <string.h>
头文件中可用。
该函数在复制源字符串后返回一个指向目标字符串的指针。
strncpy()
的语法
void *strncpy(void *destination_string, const void * source_string, size_t number);
-
destination_string
是指向目标字符串的指针。 -
source_string
是指向原始字符值数组的指针。 -
number
是字符数。
如果 strncpy()
函数在 source_string
中遇到一个空字符,该函数将在 destination_string
中添加空字符。
#include <stdio.h>#include <string.h> int main(void)
{
char *text = "The test string is here";
char subtext[7];
strncpy(subtext,&text[9],6);
subtext[6] = '\0';
printf("The original string is: %s\n",text);
printf("Substring is: %s",subtext);
return 0;
}
输出:
The original string is: The test string is here
Substring is: string
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。