好吧,我得到了一个接收二进制数据的套接字,我把那个数据变成了一个字符串,其中也包含值和字符串值。(例如“0x04,h,o,m,e,....”)
如何在该字符串中搜索十六进制子字符串?
即我想搜索“0x02,0x00,0x01,0x04”。
我要一个 c++ 版本的 python 'fooString.find("\x02\x00\x01\x04")'
谢谢大家 :)
良好的字符串文档在这里:
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));
}
c++ String object 中有很多查找选项,比如
find 在字符串中查找内容(公共成员函数)
rfind 查找字符串中最后出现的内容(公共成员函数)
find_first_of 在字符串中查找字符(公共成员函数)
find_last_of 从末尾开始查找字符串中的字符(公共成员函数)
find_first_not_of 查找字符串中缺少的字符
find_last_not_of 从末尾开始查找字符串中缺少的字符(公共成员函数)
http://www.cplusplus.com/reference/string/string/
转到上面的链接,看看哪个适合你
尝试这样的事情:
char find[] = {0x02, 0x04, 0x04, 0x00};
int pos = strstr(inputStr, find);
请记住,0x00
为空,即字符串的结尾。因此,如果您的来源或搜索包含它们,您将找不到您要查找的内容,因为strstr
将在第一个 null 处停止。
也许您可以尝试strstr()或相关函数。或者您可以使用strtok之类的东西来获取分隔符之间的值并自己解码。