我正在尝试拆分以下字符串:
"add galaxy [Milky way] elliptical 13.2B"
我想要实现的结果数组应包含以下字符串:
"add","galaxy","Milky way","eliptical","13.2B"
我尝试使用 string.Split() 并尝试了不同的方法参数,但没有达到我想要的效果。
我怎样才能达到这个结果?
编辑: 我找到了一种使用正则表达式来做到这一点的方法。
@"[A-Za-z0-9.]+|(#.*?#)|(\[.*?\])"
最佳答案
这是一个快速但肮脏的解决方案。但没有考虑多个空格或多个嵌套 [[[]]]
的可能性。
string[] split(string s)
{
List<string> list = new List<string>();
int start = 0;
int end = 0;
bool inBlock = false;
for(; end < s.Length; end++)
{
if (s[end] == '[')
{
inBlock = true;
start++;
}
else if(s[end] == ']' && inBlock)
{
inBlock = false;
list.Add(s.Substring(start, end - start));
end++;
start = end + 1;
}
else if(s[end] == ' ' && !inBlock)
{
list.Add(s.Substring(start, end - start));
start = end + 1;
}
}
if(end > start)
list.Add(s.Substring(start, end - start));
return list.ToArray();
}
关于c# - 如何拆分包含方括号且其中有空格的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67449887/