我有一个“自定义”字符串,其格式如下。例如:
std::string MyString = "RndOrder%5d - RndCustomer%8s - RndHex%8x";
我想替换/解析字符串:
%5d
(%NUM_d)将替换为随机的5位十进制
%8s
(%NUM_s)将替换为随机的8-chars
%8x
(%NUM_x)将替换为随机的8位十六进制
是否有任何功能可以帮助我解析那些“特殊标记”?不确定我是否必须通过char解析字符串char并检查每个可能的组合。
答案 0 :(得分:1)
好的,假设您实际上在这里询问字符串解析(而不是随机数/数据生成)...看看这个:
int iRandom1 = 12345; // 5-digit decimal
int iRandom3 = 0x12345678; // 8-digit hexadecimal
char cRandom2[9] = "RandomXY\0"; // Don't forget to NULL-terminate!
std::string sFormat = "RndOrder%5d - RndCustomer%8s - RndHex%8x";
char cResultBuffer[500]; // Make sure this buffer is big enough!
std::sprintf( cResultBuffer, sFormat.c_str(), iRandom1, cRandom2, iRandom3 );
std::string MyString = cResultBuffer; // MyString = "RndOrder12345 - RndCustomerRandomXY - RndHex12345678";
答案 1 :(得分:1)
它是std::snprintf
(c ++ 14)的候选者,但要注意在一次调用中请求正确的缓冲区大小,分配缓冲区然后将字符串格式化为缓冲区:
#include <iostream>
#include <cstring>
#include <string>
template<class...Args>
std::string replace(const char* format, Args const&... args)
{
// determine number of characters in output
auto len = std::snprintf(nullptr, 0, format, args...);
// allocate buffer space
auto result = std::string(std::size_t(len), ' ');
// write string into buffer. Note the +1 is allowing for the implicit trailing
// zero in a std::string
std::snprintf(&result[0], len + 1, format, args...);
return result;
};
int main() {
auto s = replace("RndOrder%5d - RndCustomer%8s - RndHex%8x", 5, "foo", 257);
std::cout << s << std::endl;
}
预期产出:
RndOrder 5 - RndCustomer foo - RndHex 101