gpt4 book ai didi

c++ - 在字符串中搜索十六进制子串

转载 作者:行者123 更新时间:2023-11-30 01:32:33 26 4
gpt4 key购买 nike

好吧,我有一个接收二进制数据的套接字,我将该数据转换为一个字符串,其中也包含值和字符串值。 (例如“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++ - 在字符串中搜索十六进制子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1487840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com