[英]Breaking a string in C with multiple spaces
好的,所以我的代碼當前將一個字符串分割成這樣:“ hello world”成:
hello
world
但是,當我在字符串之間,之前或之后有多個空格時,我的代碼不起作用。 它占用該空間並將其作為要分析的單詞/數字。 例如,如果我在hello和world之間放置兩個空格,則代碼將產生:
hello
(a space character)
world
該空格實際上算作一個單詞/令牌。
int counter = 0;
int index = strcur->current_index;
char *string = strcur->myString;
char token_buffer = string[index];
while(strcur->current_index <= strcur->end_index)
{
counter = 0;
token_buffer = string[counter+index];
while(!is_delimiter(token_buffer) && (index+counter)<=strcur->end_index)//delimiters are: '\0','\n','\r',' '
{
counter++;
token_buffer = string[index+counter];
}
char *output_token = malloc(counter+1);
strncpy(output_token,string+index,counter);
printf("%s \n", output_token);
TKProcessing(output_token);
//update information
counter++;
strcur->current_index += counter;
index += counter;
}
我可以在循環中看到問題區域,但是對於解決此問題我有些困惑。 任何幫助將不勝感激。
從編碼的角度來看,如果您想知道如何在沒有庫的情況下進行練習,那么您遇到的第一個問題就是循環中斷。 然后,當您循環到第二個定界符時,您無需輸入第二個while循環並再次打印新行。 你可以放
//update information
while(is_delimiter(token_buffer) && (index+counter)<=strcur->end_index)
{
counter++;
token_buffer = string[index+counter];
}
使用標准的C庫函數strtok()。
而不是重新開發這樣的標准功能。
這是相關的相關手冊頁 。
在您的情況下可以使用以下方法:
#include <string.h>
char *token;
token = strtok (string, " \r\n");
// do something with your first token
while (token != NULL)
{
// do something with subsequents tokens
token = strtok (NULL, " \r\n");
}
如您所見,隨后每次使用相同參數對strtok的調用都會使您將char *地址返回給下一個標記。
如果您正在處理線程程序,則可以使用strtok_r()C函數。
對其的第一次調用應與strtok()相同,但隨后的調用通過傳遞NULL作為第一個參數來完成。 :
#include <string.h>
char *token;
char *saveptr;
token = strtok_r(string, " \r\n", &saveptr)
// do something with your first token
while (token != NULL)
{
// do something with subsequents tokens
token = strtok_r(NULL, " \r\n", &saveptr)
}
只需將流程令牌邏輯放入if(counter > 0){...}
,就可以使malloc
僅在存在真實令牌時才發生。 像這樣
if(counter > 0){ // it means has a real word, not delimeters
char *output_token = malloc(counter+1);
strncpy(output_token,string+index,counter);
printf("%s \n", output_token);
TKProcessing(output_token);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.