一、HEX转字符串
uint8_t a[] = {0x12, 0x56, 0xab};
转换为 std::string str = 1256ab;
可以使用到sstream
sstream 的主要功能包括:
1、创建字符串流:可以使用 std::stringstream 构造函数创建一个字符串流。例如:std::stringstream ss;
2、向字符串流中插入或写入数据:可以使用 << 运算符向字符串流中插入或写入数据。例如:ss << “Hello, world!”;
3、从字符串流中提取或读取数据:可以使用 >> 运算符从字符串流中提取或读取数据。例如:int i; ss >> i;
4、格式化字符串流:可以使用 std::stringstream 的成员函数 str()、seekp()、tellp()、clear() 等进行格式化字符串流的操作。例如:std::string s = ss.str();
#include <iostream>
#include <sstream>
#include <string>
template<typename T>
std::string hexToStr(const T* hex, std::size_t len) {
std::ostringstream oss;
for (std::size_t i = 0; i < len; ++i) {
oss << std::hex << static_cast<int>(hex[i]);
}
return oss.str();
}
int main() {
uint8_t a[] = {0x12, 0x56, 0xab};
std::string str = hexToStr(a, sizeof(a) / sizeof(uint8_t));
std::cout << str << std::endl; // 输出结果为 "1256ab"
return 0;
}
输出结果:
1256ab
二、计算单词个数
#include <iostream>
#include <sstream>
#include <string>
class Solution {
public:
int countSegments(std::string s) {
std::istringstream input(s);
int count = 0;
std::string temp;
while (input >> temp) {
count++;
}
return count;
}
};
int main() {
Solution solution;
std::string input = "Hello, world! us dh dhjsdhf h m";
int count = solution.countSegments(input);
std::cout << "Number of segments: " << count << std::endl;
return 0;
}
输出结果:
Number of segments: 7