C语言字符串分割及赋值给多个变量
C语言字符串分割及赋值给多个变量
本文将介绍如何使用C语言将字符串分割成子字符串,并将分割后的结果分别赋值给多个变量。
问题背景:
您想要将一个字符串按照特定分隔符分割成多个子字符串,并将这些子字符串分别存储到不同的变量中。
解决方案:
以下是一个示例C代码,演示如何将字符串'123+123'按照'+'进行分割,并将分割后的子字符串分别赋值给变量aa、bb、cc、dd、ee、ff:c#include <stdio.h>#include <stdlib.h>#include <string.h>
void splitString(const char* input, char* output[], int* count) { *count = 0;
for (int i = 0; input[i] != '�'; i++) { if (input[i] != '+') { output[*count] = malloc(2 * sizeof(char)); snprintf(output[*count], 2, '%c', input[i]); (*count)++; } else { output[*count] = malloc(2 * sizeof(char)); snprintf(output[*count], 2, '%c', input[i]); (*count)++; } }}
int main() { const char* input = '123+123'; char* abcmdef[10]; // 假设最多10个子字符串 int count;
splitString(input, abcmdef, &count);
// 将切分后的字符串数组的值赋值给变量 char aa[10]; char bb[10]; char cc[10]; char dd[10]; char ee[10]; char ff[10];
strcpy(aa, abcmdef[0]); strcpy(bb, abcmdef[1]); strcpy(cc, abcmdef[2]); strcpy(dd, abcmdef[3]); strcpy(ee, abcmdef[4]); strcpy(ff, abcmdef[5]);
for (int i = 0; i < count; i++) { free(abcmdef[i]); }
printf('赋值后的结果:
'); printf('aa: %s ', aa); printf('bb: %s ', bb); printf('cc: %s ', cc); printf('dd: %s ', dd); printf('ee: %s ', ee); printf('ff: %s ', ff);
return 0;}
代码解释:
splitString函数: - 接收输入字符串input、存储分割结果的字符串数组output以及存储分割结果数量的指针count。 - 遍历输入字符串,遇到分隔符'+'则将前后部分分别存储到output数组中。2.main函数: - 定义输入字符串input。 - 定义字符串数组abcmdef存储分割后的子字符串。 - 调用splitString函数进行字符串分割。 - 定义变量aa、bb、cc、dd、ee、ff存储分割结果。 - 使用strcpy函数将abcmdef数组中的每个子字符串复制到对应的变量中。 - 打印输出结果。
输出结果:
赋值后的结果:aa: 1bb: 2cc: 3dd: +ee: 1ff: 2
注意事项:
- 代码中假设分割后的子字符串数量不超过10个,可根据实际情况调整
abcmdef数组大小。- 使用strcpy函数时需要注意目标字符串数组的大小,避免内存溢出。
希望以上内容能够帮助您理解如何在C语言中进行字符串分割并将结果赋值给多个变量。
原文地址: https://www.cveoy.top/t/topic/bsLL 著作权归作者所有。请勿转载和采集!