解析字符串给出:#parameter1~value1#parameter2~value2#parameter3

Parsing string given by: #parameter1~value1#parameter2~value2#parameter3

本文关键字:#parameter1 value1#parameter2 value2#parameter3 字符串      更新时间:2023-10-16

有人能给我一些提示,什么是最好的/优雅的方法来提取参数名称和参数值从可变长度输入字符串?我需要提取这些值,以便将它们写在另一个.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.....

最好的方法是使用javaStringTokenizer。代码如下所示:

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函数。更多信息请参见此处