gpt4 book ai didi

c++ - 如果该分隔符包含在方括号中,我如何通过分隔符拆分 QString 而不是

转载 作者:行者123 更新时间:2023-11-28 02:05:57 25 4
gpt4 key购买 nike

如果我有一个形式为 QString s = QString("A:B[1:2]:C:D"); 的 QString,我想以某种方式拆分为 ' :',但前提是没有用方括号括起来。

所以上面QString的输出应该是"A", "B[1:2]", "C", "D"

现在,我只能想到在 s.indexOf('[')s.indexOf 范围内替换 ':' (']'),然后拆分,然后在任何剩余的拆分中替换回 ​​':',但这似乎很不方便。

编辑:基于评论和答案:方括号中的任何数字在拆分后都应相同。有字符,例如:';'我可以使用 t 作为“:”的临时替代品

有更好的主意吗?

最佳答案

通常,我喜欢在这里直接使用正则表达式进行拆分的想法,但我不能很快想出一个。因此,您的想法是首先用其他东西(这里是分号)替换不需要的冒号,然后拆分剩余的冒号并将分号替换回单独字符串上的冒号。

#include <QDebug>
#include <QRegularExpression>
#include <QString>

int main()
{
QString string("A:B[1:2]:C:D");

// This replaces all occurences of "[x:y]" by "[x;y]" with
// x and y being digits.
// \\[ finds exactly the character '['. It has to be masked
// by backslashes because it's a special character in regular
// expressions.
// (\\d) is a capture for a digit that can be used in the
// resulting string as \\1, \\2 and so on.
string = string.replace(QRegularExpression("\\[(\\d):(\\d)\\]"), "[\\1;\\2]");

// split on the remaining colons
QStringList elements = string.split(':');

// Iterate over all fractions the string was split into
foreach(QString element, elements) {
// Replace the semicolons back to colons.
qDebug() << element.replace(QRegularExpression("\\[(\\d);(\\d)\\]"), "[\\1:\\2]");
}
}

输出:

"A"
"B[1:2]"
"C"
"D"

关于c++ - 如果该分隔符包含在方括号中,我如何通过分隔符拆分 QString 而不是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37525491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com