2017-04-16 56 views
0

我有數據字符串,它看起來像:3,1,6,IN,88。 我需要只有第3個週期(3 | 1 | 6 | IN,88) 因此,將停止循環的最後,和最後一個字符串之前將IN,88限制strtok只有3個標記

char *pch=strtok (data,","); 
while (pch != NULL) 
     { 
      //works well here 
      pch = strtok (NULL, ","); 
     } 

這將也分裂IN,88,我想保留它在內部的逗號。

只要設置一個計數器在3中斷就顯然不起作用。 有沒有簡單的方法來實現這一點,而不改變數據?

+1

嘗試使用'for'循環代替嗎? –

+0

我必須在這裏高效。其硬件。所以你的意思是使用strtok for循環? – Curnelious

+0

嘗試使用爲最後一個標記設置的不同分隔符,以免在逗號處中斷。 –

回答

0

您需要在標記之後原始字符串的非原文部分。您還需要將輸入字符串標記爲指定的次數。你可以試試這個。

char *tmp; // will store the untokenized part of the string 
int count; // how many times the string will be tokenized 
tmp = data; // before starting to tokenize, the whole input is untokenized 
char *pch = strtok (data,","); 
count = 1; 
while (pch != NULL && count <= 3) // you want to tokenize thrice 
{ 
    tmp = tmp + strlen(pch) + 1; // shift the pointer pointing untokenized string 
    pch = strtok(NULL,","); 
    count++; 
} 
tmp = tmp + strlen(pch) + 1; // shift the pointer after last tokenization 

在此之後,如果你做puts(tmp);,你將得到的字符串作爲輸出的非記號部分。