我试图解析一个字符串,如:
"12 13 14 16"
对于数组中的5个数字.
我使用strtok(string_above,“”),但strtok()将这三个空白字符作为一个.我该怎么做才能防止它?
最佳答案 我确实喜欢这样做,这可能是你需要的.我没有广泛测试它,但它通过了一个简单的测试.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int
main(void)
{
char string[] = "12 13 14 16";
char *current;
char *next;
int done;
current = string;
done = 0;
while (done == 0)
{
next = strchr(current, ' ');
if (next == NULL)
next = strchr(current, '\0');
// If there are no more tokens, current[0] will be
// equal to 0 and (end == current) too
done = (current[0] == '\0');
if ((next != current) && (done == 0))
{
// We nul terminate it (replace the delimiter with nul)
// so now, current is the token.
next[0] = '\0';
// Display the token
printf("--%s--\n", current);
// Restore the character
next[0] = ' ';
// Advance to the next characeter (for the next strchr())
current = next + 1;
}
else if (*next++ == ' ') // If the next character is a space,
{ // it's a delimiter
int spaces;
int count;
// Count the number of spaces to see
// if the space is a delimiter or a token
spaces = 1;
// Count the number of tokens
count = 1;
// While the current character is a space, we seek for a non-space
while (isspace((unsigned char) *next) != 0)
{
next++;
if (spaces % 2 == 0) // If it's an even space (it's a token)
count += 1;
spaces++;
}
// If the spaces variable is not even
// there was no delimiter for the last
// token consider this an input error
if (spaces % 2 != 0)
return -1;
// Print the blanks as 0's
for (int i = 0 ; i < count ; ++i)
printf("--0--\n");
// Advance to the next characeter (for the next strchr())
current = next;
}
}
return 0;
}