c++ - How to compare "4A4B4C"(string shows hex value) 实际字符串是 "JKL"

标签 c++ string hex string-comparison

我得到一个字符串 "4A4B4C4D4E4F".. 它等于一个字符串 ("JKLMNO")

我如何在 C++ 中检查这种类型的字符串..(一个字符串显示另一个字符串的十六进制表示)

十六进制值

J=4A, K=4B, L=4C

最佳答案

或者,这可以使用 C++ 字符串和特性而不是 C 风格的字符串来完成:

#include <iostream>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <iomanip>
#include <string>

bool compareAscii(const std::string& string, const std::string& asciistr) {
   std::ostringstream result;
   result << std::setw(2) << std::setfill('0') << std::hex << std::uppercase;
   // We copy the contents of string, using the range from the beginning to the end.
   // By copying it to an ostream iterator it gets written to the ostringstream,
   // but crucially we treat it as an unsigned int when we write it, which causes
   // the chars to get printed as their numerical values instead.
   std::copy(string.begin(), string.end(), std::ostream_iterator<unsigned int>(result));
   return result.str() == asciistr;
}

namespace {
   const std::string test="JKLMNO";
   const std::string value="4A4B4C4D4E4F";
}

int main() {
   std::cout << "compareAscii(\"" << test << "\", \"" << value << "\") returned " << compareAscii(test, value) << std::endl;
   return 0;
}

关于c++ - How to compare "4A4B4C"(string shows hex value) 实际字符串是 "JKL",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6212987/

相关文章:

java - 查找字符串中存在的字符 :java

c++ - 在C++中对 vector 的内容进行排序

c++ - Func A 调用 Func B,反之亦然(为什么它不起作用)

c++ - 为什么不总是在堆栈上实例化对象? C++

c - 在 C 中作为用户输入的文件路径

c - 使用 strpbrk 分隔字符串,分隔符为 ">>"?

python - 如何使用十六进制 Ascii 中特定位数的字符串格式

xml - 从 xml 文件的 vb.net 十六进制扫描

数组名称的 C++ 值

c++ - 在不使用任何 std::string 成员函数的情况下从 std::string 对象显式转换为 char*