我有一个字符串,例如“123 789”,我想要的结果是将此输出的字符串分开:
123
789
我已经创建了完成此操作的代码,通过查找空格来分隔字符串。
我需要帮助来编辑我的代码,以通过回车符、换行符、垂直制表符、自由格式制表符或一系列空格来分隔字符串。基本上,任何空白字符。目前,如果除了一个空格以外的任何东西分隔字符串的不同部分,我的代码就会中断。
这是我的代码,目前由一个空格分隔:
int counter = 0; //counter used in loop
int index = test->current_index; //holds the current index of my string, it's initially 0
char *string = test->myString; //holds the whole string
char token_buffer = string[index];
//before loop: index = 0, counter = 0
while(test->current_index <= test->end_index)
{
counter = 0;
token_buffer = string[counter+index];
while(token_buffer != ' ' && (index+counter)<=test->end_index)
{
counter++;
token_buffer = string[index+counter];
}
char *output_token = malloc(counter+1);
strncpy(output_token,string+index,counter);
printf("%s \n", output_token);
TestProcessing(output_token); //sends each token to be processed further
//update information
counter++;
test->current_index += counter;
index += counter;
return 0;
}
最佳答案
要像这样定义一个 util 函数,
int is_delimiter(char c)
{
char delimiters[] = {'\0','\n','\r',' '};//customize to expand
for(int i = 0; i < sizeof(delimiters); i++){
if(delimiters[i] == c)
return 1;
}
return 0;
}
然后,
while(!is_delimiter(token_buffer) && (index+counter)<=test->end_index)
关于c - 用C中的任何空格分隔字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31106440/