描述:
在 C 语言中,可以使用字符串处理函数来截取某字符串的某一片段字符串。下面是一个示例代码,演示了如何提取字符串 char str[] = {‘+’,‘C’,‘S’,‘Q’,‘:’,‘2’,‘8’,‘,’,‘9’,‘9’,‘a’}; (即"+CSQ:28,99a")的某一片段字符串“28,99”:
#include <stdio.h>
#include <string.h>
/******************************************/
//说明 :此函数用于截取字符数组的某一段数据,即切片操作。
//参数 str: 需要操作的字符数组,如{'+','C','S','Q',':','2','8',',','9','9','a'}
//参数 start:起始字符串或者字符,比如"+CS",或者单个字符"C"开始。截取片段不包括此字符或字符串
//参数 end:结束字符,注意是字符不是字符串。比如'a',截取片段不包括此字符
//例子:
// char str[] = {'+','C','S','Q',':','2','8',',','9','9','a'};
// start = ":"
// end = ','
// return new array = {'2','8'}
unsigned char *Array_Splitting(unsigned char *str, unsigned char *start, unsigned char end)
{
int i = 0;
static unsigned char new_array[] = {0};
unsigned char *pStart = strstr(str, start); // 找到子字符串 start的首地址
if (pStart != NULL)
{
pStart += strlen(start); // 将指针移动到 start 字符串的结尾
while(*pStart != end) new_array[i++] = *pStart++;//将字符串start后,字符end前的字符存到新数组
}
return new_array;
}
int main() {
char str[] = {'+','C','S','Q',':','2','8',',','9','9','a','\0'};
// 等价于char str[] ="+CSQ:28,99a"
char *c = Array_Splitting(str, ":", 'a');
for(int j = 0;j < 10; j++)
{
printf("c[%d] = %c\r\n", j, c[j]);
}
return 0;
}
运行结果
c[0] = 2
c[1] = 8
c[2] = ,
c[3] = 9
c[4] = 9
c[5] =
c[6] =
c[7] =
c[8] =
c[9] =
本人技术水平有限,如果有大佬有更好的方案或者说改进,欢迎在评论区交流。