解析字符串给出:#parameter1~value1#parameter2~value2#parameter3
Parsing string given by: #parameter1~value1#parameter2~value2#parameter3
有人能给我一些提示,什么是最好的/优雅的方法来提取参数名称和参数值从可变长度输入字符串?我需要提取这些值,以便将它们写在另一个.txt文件中。我应该使用正则表达式吗?如何使用它们呢?
我知道如何做到这一点,但使用for循环和各种if-then条件,这是一个烂摊子。我需要的是去哪里找一些可以帮助我的内置功能。
谢谢!
在这种情况下,正则表达式是不必要的开销。单个字符的std::string::find
就足以完成这项工作。假设每个参数(即使是第一个)以#
开头,该值是可选的(默认是""
),并且始终省略末尾的#
,您可以这样做:
std::string pstr = ...; // the parameter string
typedef std::pair<std::string, std::string> Param;
std::vector<Param> params;
std::size_t pos = pstr.find('#');
std::size_t next = pstr.find('#', pos);
while (pos != std::string::npos) {
std::string param, value;
std::size_t sep_pos = pstr.find('~', next);
if (sep_pos != std::string::npos) {
value = pstr.substr(sep_pos + 1, next - sep_pos - 1);
param = pstr.substr(pos + 1, sep_pos - pos - 1);
} else {
param = pstr.substr(pos + 1, next - pos - 1);
}
params.push_back(Param(param, value));
}
注意,std::strtok
是一个不好的建议。这个函数是不安全的,不应该在普通的c++代码中使用。
假设存储的初始文本如下:
param1:value1;param2:value2;param3:value3.....
最好的方法是使用java
的StringTokenizer
。代码如下所示:
StringTokenizer sT=new StringTokenizer(InputString, ";");
while(sT.hasMoreTokens())
{
String Pair=sT.nextToken();
String sT2=new StringTokenizer(Pair, ":");
String param=sT2.nextToken();
String value=sT2.nextToken();
System.out.println(param+" "+value);
}
另一方面,如果你想严格使用C++
编码,那么你可以使用c++计数器部分,strtok
函数。更多信息请参见此处
相关文章:
- 'val' Arduino 错误代码之前的预期'('
- C++算法标头中,为什么要使用 "!(val < *first)" ?
- C++ 一个lambda浅拷贝const Type&如果它被赋予一个命名捕获,如[copy=val](){}?
- 为什么 std::find( s.begin(), s.end(), val ) 比集合 s 的 s.find(val) 慢 1000 倍<int>?
- APInt(unsigned numBits, uint64_t val, bool isSigned = false)
- 在模板元编程中使用"struct xxx<>::val"导致错误
- SWIG:包装 std::map<key 时编译器错误,val *>
- C++ std::map::find to C# 字典<键,val>
- val != std::numeric_limits:<double>:infinity() 或 !isinf(val) 或 isfinite(val)
- 在 for (int val :arr) 中,冒号是什么意思
- 使用 std::transform 将 std::vector<struct{key; val;}> 转换为 std::map<key, val>
- IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX_V2 Constant Val
- 为什么 std::map 没有 insert(key &k, val &v) 类型的插入函数
- C++ code for do Python struct.pack('>I',val)
- C++ 异常情况下的错误 C2228(".val"的左侧必须具有类/结构/联合)
- #pragma 注释(链接器,"/STACK:val"),哪个基础值可以?
- Java 等效于 C++ 的模板 <int val> class foo{ };
- istream的运算符之间的差异>>libc++和libstdc++之间的double&val)
- std::vector:<T>:resize( n, val ) 是否足以进行初始化?
- Char Val = 'ABCD'。使用多字符字符