2013-05-08 77 views
-2

我想從字符串一些像這樣的信息:如何解析路徑樣串用C

[email protected]/devices/pci0000:00/0000:00:11.0/0000:02:03.0/usb1/1-1/1-1:1.0/host26/target26:0:0/26:0:0:0/block/sdh/sdh1 

[email protected]/devices/pci0000:00/0000:00:11.0/0000:02:03.0/usb1/1-1/1-1:1.0/host26/target26:0:0/26:0:0:0/block/sdh/sdh1 

我想要得到的信息是第一個字的「添加」 /「刪除」和最後一個字「SDH1」。

我將非常感謝您的幫助!

謝謝!

+5

你好,歡迎來到SO!你嘗試了什麼?什麼沒有用?請告訴我們您已經完成了一些研究工作。 – 2013-05-08 07:49:24

回答

0

您可以查看標準函數strtok(3),它允許您將字符串拆分爲由某個字符分隔的子字符串,在'/'的情況下。

在這種情況下,另一個也許更簡單的方法是使用index(3) and rindex(3)。使用索引找到第一個'@'並從開頭複製到該索引。並使用rindex找到最後的'/',並從該索引複製到字符串的末尾。

+0

strtok破壞了它工作的字符串,所以如果你想保留你的原始字符串,然後將它複製到一個工作字符串傳遞給strtok。 – 2013-05-08 07:56:25

1

搜索 '@' 和strchr通過和strrchr

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

int main(void){ 
    char str1[]="[email protected]/devices/pci0000:00/0000:00:11.0/0000:02:03.0/usb1/1-1/1-1:1.0/host26/target26:0:0/26:0:0:0/block/sdh/sdh1"; 
    char str2[]="[email protected]/devices/pci0000:00/0000:00:11.0/0000:02:03.0/usb1/1-1/1-1:1.0/host26/target26:0:0/26:0:0:0/block/sdh/sdh1"; 
    char first[32],last[32], *cp; 
    char *datas[] = {str1, str2 }; 
    int i; 

    for(i=0;i<2;++i){ 
     cp=strrchr(datas[i], '/'); 
     strcpy(last, cp+1); 
     cp=strchr(datas[i], '@'); 
     *cp='\0';//destroy the original!! 
     strcpy(first, datas[i]); 
     printf("%s, %s\n", first, last); 
    } 
    return 0; 
} 
+3

如果你不提供這樣的問題的實際代碼,這將是很好的。我們不想鼓勵「給我解碼器」類型的問題。 – Shahbaz 2013-05-08 08:04:59

+0

我認爲一個樣本可以幫助初學者理解。 – BLUEPIXY 2013-05-08 08:09:35

+0

@Shahbaz:我很抱歉,但這很愚蠢。如果問題不夠好,請關閉它。但除此之外,答案應始終儘可能有幫助和詳細。假設有人正在尋找同樣的問題,那麼實際的代碼就是他們想要找到的。 – Timo 2013-05-08 08:28:32

0

搜索最後 '/' 看看POSIX函數basenamedirname,如果你是POSIX系統。