我得到一个字符串 "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/