【发布时间】:2017-08-02 00:13:08
【问题描述】:
我正在自学 C 编程。 我正在尝试计算给定字符串中存在的以空格分隔的 int 数。
表达式: 输入str =“1 2 11 84384 0 212” 输出应为:1、2、11、84384、0、212 总整数 = 6
当我尝试时。它给了我所有有意义的数字作为输出,因为我在这里没有使用正确的方法。
我知道在 python 中我可以使用 str.split (" ") 函数,它可以很快完成我的工作。
但我想在 C 中尝试类似的东西。尝试创建自己的拆分方法。
#include <stdio.h>
#include <string.h>
void count_get_ints(const char *data) {
int buf[10000];
int cnt = 0, j=0;
for (int i=0; i<strlen(data); i++) {
if (isspace(data[i] == false)
buf[j] = data[i]-'0';
j++;
}
printf("%d", j);
}
// when I check the buffer it includes all the digits of the numbers.
// i.e for my example.
// buf = {1,2,1,1,8,4,3,8,4,0,2,1,2}
// I want buf to be following
// buf = {1,2,11,84384,0,212}
我知道这不是解决此问题的正确方法。一种跟踪 prev 并使用遇到的非空格数字动态创建内存的方法。 但我不确定这种方法是否有帮助。
【问题讨论】:
-
如果您有 1 位整数,您的方法可能有效,但您的整数跨越多个符号。作为提示,您需要找出整数在字符串中开始的位置。然后您可以使用
strtol函数将字符串开头的部分转换为整数。