根据左侧的分隔符将字符串拆分为子字符串

时间:2018-05-16 14:55:19

标签: c# string split

在c#中,是否有一种优雅的方法可以将像“a.b.c”这样的字符串拆分为a,a.b,a.b.c
分隔符的数量不固定,因此它可以是“a.b”,它将输出{a,a.b}或“a.b.c.d”,它将输出{a,a.b,a.b.c,a.b.c.d}。

我唯一能想到的是将字符串拆分为单个组件,然后再次连接它。

这是我到目前为止所做的:

ERROR:  operator does not exist: record = text
LINE 4: ON f = day_of_year group by d order by d asc;
         ^
HINT:  No operator matches the given name and argument type(s). You might 
need to add explicit type casts.

2 个答案:

答案 0 :(得分:2)

也许这个扩展名?

public static string[] SplitCombineFirst(this string str, params string[] delimiter)
{
    string[] tokens = str.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
    var allCombinations = new List<string>(tokens.Length);
    for(int take = 1; take <= tokens.Length; take++)
    {
        string combination = string.Join(delimiter[0], tokens.Take(take));
        allCombinations.Add(combination);
    }
    return allCombinations.ToArray();
}

呼叫:

string[] result = "a.b.c".SplitCombineFirst(".");

答案 1 :(得分:0)

这看起来像递归的经典案例。

List<string> splitCombine(string source, string delimiter, int startIndex)
{
    List<string> result = new List<string>();
    var indx = source.IndexOf(delimiter, startIndex);
    if (indx >= 0)
    {
        if (indx > 0)
        {
            result.Add(source.Substring(0, indx));
        }
        result.AddRange(splitCombine(source, delimiter, ++indx));
    }
    else
    {
        result.Add(source);
    }
    return result;
}

呼叫:

var result = splitCombine("a.b.c.d.e", ".", 0);