c# - 如何拆分包含方括号且其中有空格的字符串

标签 c# arrays string split format

我正在尝试拆分以下字符串:

"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/

相关文章:

javascript - 从数组中获取最合适的匹配字符串

java - 将各种符号的字符串转换为整数

java - 我想阅读此表格内的内容

c++ - 如何从函数返回字符串文字

c# - 在给定用户已经有 cookie 的情况下启动应用程序时处理 null HttpContext.Current

C# 从 Color 获取所有颜色

java - 在 C# 中使用 getBytes() 从 SQL 中获取数据(提供了 JAVA 代码)

javascript - 使用类/构造函数与变量方法时的范围不同

c# - 如何让程序自动以管理员身份运行

c# - Rhino Mocks 在 Debug模式下表现出不同的行为