问题描述
我正在放在一起的C应用程序中有一个逗号分隔的字符串,我想将其拆分为整数值数组。
该字符串可以包含任意数量的逗号分隔值,因此我也没有数组的初始大小。
I have a comma delimited string in a C app that I'm putting together and I want to split it into an array of integer values.The string could contain any number of comma delimited values so I also dont have an initial size for the array.
例如。
"345,3345,35,75,52,386"
和id喜欢做类似的事情...
and id like to do something like...
int parsedArray[] = parseString("345,3345,35,75,52,386");
这在Java或C#中都是轻而易举的,但我认为我有点不了解涉及到C。
关于如何实现此目标的任何想法吗?
This would be a breeze in java or c# but I think I'm a little out of my depth when it comes to C.Any ideas of how to achieve this?
推荐答案
签名暗含的函数在C中无法发表您的文章,因为函数无法返回动态大小的数组。这里有两个选择:
A function with the signature implied in your post is not possible in C, because a function cannot return a dynamically-sized array. Two choices are possible here:
- 将数组和最大计数传递到
parseString
,或 - 返回表示动态分配的数组及其实际大小的指针。
- Pass an array and the max count into
parseString
, or - Return a pointer representing a dynamically allocated array, along with its actual size.
第一种方法将数组的大小限制为调用者确定的某个数字;第二种方法要求在完成处理后重新分配数组。
The first approach limits the size of the array to some number established by the caller; the second approach comes with a requirement to deallocate the array once you are done with it.
第一种方法的功能如下:
The function that follows the first approach would look like this:
void parseString(int data[], size_t maxSize);
第二种方法的功能如下:
The function that follows the second approach would look like this:
int *parseString(size_t *actualSize);
或类似这样:
void parseString(int ** data, size_t *actualSize);
第二种情况可以用来组合这两种方法,尽管API会变得不太直观。
The second case can be used to combine the two approaches, although the API would become somewhat less intuitive.
至于解析本身,存在许多选项。 轻量级选项之一是使用 strtol
,例如:
As for the parsing itself, many options exist. One of the "lightweight" options is using strtol
, like this:
char *end = str;
while(*end) {
int n = strtol(str, &end, 10);
printf("%d\n", n);
while (*end == ',') {
end++;
}
str = end;
}
这篇关于在C中将字符串拆分为整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!