2013-08-22 22 views
0

我正在用c編程語言編寫一個TCP客戶端應用程序,該項目是一個客戶端服務器通信。我正在成功地與服務器通信,並且服務器像字符串一樣向我發送命令,我將該字符串保存在圖表陣列中,然後執行,但問題是有時服務器發送的命令多於一個(max 3命令) [100#100#100#] 100是命令,#是符號,所以我知道第一個命令結束的位置。 所以現在的問題是如何劃分一個單獨的字符數組中的所有命令?任何ide將一個命令從一個帶有分隔符的命令數組中分離出來#

P.S問題爲什麼會發生這種情況是因爲客戶端是用c編寫的,而服務器是用java編程語言編寫的,客戶端不應該等待服務器的ack。

+1

使用'strtok'。搜索谷歌更多的。如果您需要可重入版本,請使用'strtok_r'。 –

回答

3

您不必命令分成獨立的char陣列 - 所有你需要的是與\0是你們等接收的字符數組內的替換# S,並保存「休息」的位置串。這裏有一個例子:

Index: 0 1 2 3 4 5 6 7 8 9 10 11 12 
     --- --- --- --- --- --- --- --- --- --- --- --- --- 
Char: '1' '0' '0' '#' '2' '0' '0' '#' '3' '0' '0' '#' \0 

Index: 0 1 2 3 4 5 6 7 8 9 10 11 12 
     --- --- --- --- --- --- --- --- --- --- --- --- --- 
Char: '1' '0' '0' \0 '2' '0' '0' \0 '3' '0' '0' \0 \0 

和存儲指針代替這&str[0]&str[4]&str[8]爲指針,以你個人的命令。

char[] str = "100#200#300#"; 
char *p1 = str; 
char *p2 = strchr(p1, '#'); 
// Replace the first '#' 
*p2++ = '\0'; 
// Replace the second '#' 
char *p3 = strchr(p2, '#'); 
*p3++ = '\0'; 
// Replace the third '#' 
*strchr(p3, '#') = '\0'; 
printf("One='%s' Two='%s' Three='%s'\n", p1, p2, p3); 

這只是一個演示:在生產代碼,你需要做任務之前檢查的strchr的返回值。

+1

這就是斯托克所做的。沒有重寫函數 – SamFisher83

+0

@ SamFisher83'strtok'不是線程安全的點是足夠的理由來重寫這個。此外,使用'strtok'就像用錘子拍打蒼蠅。 – dasblinkenlight

+0

好的,謝謝,這是行得通的,但是你能告訴我怎樣才能像變量一樣獲得p1,p2和p3,因爲我需要在我的程序中更遠的邏輯中使用它們? –

0
#include <stdio.h> 
#include <string.h> 

int main() 
{ 
    char string[] ="100#100#100"; 
    char * commands; 

    commands= strtok (str,"#"); 
    while (commands!= NULL) 
    { 
    printf ("%s\n",commands); 
    commands = strtok(NULL, "#"); 

    } 
    return 0; 
} 
+1

對不起@ samFisher83但這是錯誤的。檢查「man strtok」。 –

+0

@ManojAwasthi請解釋你爲什麼認爲這個答案是錯的。 –

+0

你應該解釋你的代碼是如何工作的,不僅是對於OP,而且對於有類似問題的未來訪問者也是如此。 –

0

使用此實現。

#include <stdio.h> 
#include <string.h> 

int main() 
{ 
    char string[] ="100#100#100"; 
    char * commands; 

    commands= strtok (string,"#"); 
    printf("%s\n", commands); // <=== this is the first token 

    while (commands!= NULL) { 
     commands= strtok (NULL,"#"); // <=== this will give further tokens 
            // Note - you need to call strtok again 
            // Note2 - you need to call with parameter NULL 
            //   for further tokens 
     printf ("%s\n",commands); 
    } 


    return 0; 
}