cpp以和分割分割字符串但这两个字符在引号范围内时不分割
要实现这个功能,可以使用一个标志变量来表示当前是否在引号范围内,并且只在不在引号范围内时才进行分割。
下面是一个示例代码:
#include <iostream>
#include <vector>
#include <string>
std::vector<std::string> splitString(const std::string& input) {
std::vector<std::string> result;
bool inQuotes = false;
std::string currentString;
for (char c : input) {
if (c == '(' && !inQuotes) {
if (!currentString.empty()) {
result.push_back(currentString);
currentString.clear();
}
} else if (c == ')' && !inQuotes) {
if (!currentString.empty()) {
result.push_back(currentString);
currentString.clear();
}
} else if (c == '"') {
inQuotes = !inQuotes;
currentString += c;
} else {
currentString += c;
}
}
if (!currentString.empty()) {
result.push_back(currentString);
}
return result;
}
int main() {
std::string input = "this is a (sample) string with (parentheses) but (not in \"quotes\")";
std::vector<std::string> result = splitString(input);
for (const std::string& str : result) {
std::cout << str << std::endl;
}
return 0;
}
输出结果:
this is a
sample
string with
parentheses
but
not in "quotes"
在这个示例代码中,我们首先定义了一个splitString函数来进行字符串分割。函数使用一个result向量来存储分割后的子串。我们遍历输入字符串中的每个字符,并根据当前字符和引号标志变量的状态来判断是否需要进行分割。在遍历结束后,我们将最后一个子串添加到result中,并返回最终结果。
在main函数中,我们定义了一个示例输入字符串,并调用splitString函数进行分割。然后,我们遍历分割后的结果并输出每个子串
原文地址: https://www.cveoy.top/t/topic/h2F5 著作权归作者所有。请勿转载和采集!