2009-09-28 75 views
1

嗯,我有一個接收二進制數據的套接字,我將這些數據轉換爲字符串,包含值和字符串值。 (例如「0x04,h,o,m,e,...」)搜索字符串中的十六進制子字符串

如何搜索到該字符串的十六進制子串?

I.e.我想搜索「0x02,0x00,0x01,0x04」。

我問一個C++版本蟒 'fooString.find( 「\ X02 \ X00 \ X01 \ X04」)' 的

感謝所有:)

回答

3

字符串良好的文檔是在這裏:
http://www.sgi.com/tech/stl/basic_string.html

六角令牌傳遞一樣的Python(如果你認爲Python得到了來自語法)。
字符\ x ??是一個十六進制字符。

#include <iostream> 
#include <string> 


int main() 
{ 
    std::cout << (int)'a' << "\n"; 
    std::string    x("ABCDEFGHIJKLMNOPabcdefghijklmnop"); 
    std::string::size_type f = x.find("\x61\x62"); // ab 


    std::cout << x.substr(f); 

    // As pointed out by Steve below. 
    // 
    // The string for find is a C-String and thus putting a \0x00 in the middle 
    // May cause problems. To get around this you need to use a C++ std::string 
    // as the value to find (as these can contain the null character. 
    // But you run into the problem of constructing a std::string with a null 
    // 
    // std::string find("\0x61\0x00\0x62"); // FAIL the string is treated like a C-String when constructing find. 
    // std::string find("\0x61\0x00\0x62",3); // GOOD. Treated like an array. 

    std::string::size_type f2 = x.find(std::string("\0x61\0x00\0x62",3)); 
} 
+0

這裏唯一的小問題是創建一個std :: string實例,其中包含null字符,對於Ragnagards示例字符串。要做到這一點,您需要std :: string構造函數,它需要一個字符數組和一個長度... size_t pos = fooString.find(std :: string(「\ x02 \ x00 \ x01 \ x04「,4)); – Steve314 2009-09-28 16:45:46

+0

你的回答全滿我的要求,謝謝你們倆:D – Ragnagard 2009-09-28 18:26:37

0

或許你可以嘗試strstr()或一個相關的功能。或者你可以使用像strtok這樣的東西來獲取你的分隔符之間的值並自己解碼。

+0

的問題是,的strstr()和其他C字符串函數上C字符串其是NUL終止,並因此不與OP的樣品搜索字符串工作工作。 – mjv 2009-09-28 16:12:53

+0

他說他正在將他的數據流中的數據轉換爲他想要搜索的字符串。我認爲他在進行轉換時沒有終止。 – 2009-09-28 16:19:32

+0

strtok()是一個壞主意,因爲它修改了底層數據以跟蹤其當前位置。 – 2009-09-28 16:25:38

2

有很多C++中的String對象查找選項,就像

找到查找字符串內容(公共成員函數)

RFIND查找的字符串內容最後一次出現(公共成員功能)字符串

find_first_of查找字符(公共成員函數)

find_last_of在串查找字符從端(公共成員函數)在字符串

find_last_not_of在串查找不存在字符的從端部(公共成員函數

find_first_not_of查找不存在字符的)

http://www.cplusplus.com/reference/string/string/

轉到上面的鏈接,看看哪些西裝是你

+0

找到完全匹配我的需求,但我怎麼能把十六進制值列表成一個字符串作爲參數傳遞給「查找」? 謝謝 – Ragnagard 2009-09-28 16:13:39

+0

使用stringstream來構建輸入參數 – Satbir 2009-09-28 16:22:33

+0

,並且對於您正在搜索的文字字符串,使用與Python中相同的語法:string sSearchPattern =「\ x02 \ x00 \ x01 \ x04」; (請注意,python字符串比C字符串更類似於C++字符串,後者是nul結尾的,因此不能在字符串中包含任何nul字符 – mjv 2009-09-28 16:46:25

0

嘗試是這樣的:

char find[] = {0x02, 0x04, 0x04, 0x00}; 
int pos = strstr(inputStr, find); 

記住,0x00是空的,即字符串的結尾。因此,如果您的來源或搜索包含它們,您將無法找到您要查找的內容,因爲strstr將在第一個null處停止。

相關問題