C中的双重分裂 [英] Double split in C
问题描述
好的.例如,我的 txt 文件中有这一行:
OK. For example I have this line in my txt file:
1|1,12;7,19;6,4;8,19;2,2
如您所见,它有 2 个部分,由 |
分隔.我得到两个部分都没有问题,并使用 ;
分隔符分隔第二部分 1,12;7,19;6,4;8,19;2,2
.但是我确实在通过 ,
进一步分离以获得每个集合的第一个和第二个数字时遇到问题.
1|1,12;7,19;6,4;8,19;2,2
As you can see, it has 2 parts, separated by |
. I have no problems getting both parts, and separating second part 1,12;7,19;6,4;8,19;2,2
using ;
separator. BUT I do have problems with separating further by ,
to get first and second number of each set.
这是我当前的代码:
result = strtok(result, ";");
while(result != NULL ) {
printf("%s\n", result);
result = strtok(NULL, ";");
}
它输出我:
1,12
7,19
6,4
8,19
2,2
1,12
7,19
6,4
8,19
2,2
好的,太好了.但是当我尝试strtok"时(我正在使用这种方法进行拆分)像这样:
OK, great. But when I try to 'strtok' (I'm using this method for splitting) like this:
result = strtok(result, ";");
while(result != NULL ) {
//printf("%s\n", result);
help = strtok(result, ",");
while(help != NULL) {
printf("<%s>", help);
help = strtok(NULL, ",");
}
result = strtok(NULL, ";");
}
我只得到 "<1>,<12>" 就像在这组数字中只有一组一样.我不明白其余的数字在哪里.相反,输出应该是:<1>、<12>、<7>、<19>、<6>、<4>、<8>、<19>、<2>,<2>.有人可以给出解决方案,如何获得每组数字的每个数字.也许还有其他方法,或者我做错了什么:)
I only get "<1>,<12>" like there is only one set in this set of numbers. I dont understand where are the rest of the numbers. Instead, output should be: <1>,<12>,<7>,<19>,<6>,<4>,<8>,<19>,<2>,<2>. Could someone please give a solution, how to get EACH number of each set this set of numbers. Maybe there are other methods or I'm doing something wrong :)
谢谢!
推荐答案
char *strtok(char *str, const char *delim);(来自手册页)
delim 参数指定一组字符,用于分隔解析字符串中的标记.在解析相同字符串的连续调用中,调用者可以在 delim 中指定不同的字符串.
char *strtok(char *str, const char *delim); (from man pages)
The delim argument specifies a set of characters that delimit the tokens in the parsed string. The caller may specify different strings in delim in successive calls that parse the same string.
因此,同时使用 ;
和 ,
作为分隔符来获取所有数字.
So, use both ;
and ,
as delimiter to get all the numbers.
//this will delimit result whenever ";" or "," is found
result = strtok(result, ";,");
while(result != NULL ) {
printf("%s\n", result);
result = strtok(NULL, ";,");
}
这篇关于C中的双重分裂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!