云在青天部落阁

独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
扩大
缩小

C#字符串处理之分割字符串并保留分隔符的几种方法

目录

  • [方法一]

    string[] parts = Regex.Split(originalString, @"(?<=[.,;])")

  • [方法二]

    public static IEnumerable SplitAndKeep(this string s, char[] delims)
    {
    int start = 0, index;

    while ((index = s.IndexOfAny(delims, start)) != -1)
    {
    if(index-start > 0)
    yield return s.Substring(start, index - start);
    yield return s.Substring(index, 1);
    start = index + 1;
    }

    if (start < s.Length)
    {
    yield return s.Substring(start);
    }
    }

  • [方法三]

    public static IEnumerable SplitAndKeep(string s, params string[] delims)
    {
    var rows = new List() { s };
    foreach (string delim in delims)//delimiter counter
    {
    for (int i = 0; i < rows.Count; i++)//row counter
    {
    int index = rows[i].IndexOf(delim);
    if (index > -1
    && rows[i].Length > index + 1)
    {
    string leftPart = rows[i].Substring(0, index + delim.Length);
    string rightPart = rows[i].Substring(index + delim.Length);
    rows[i] = leftPart;
    rows.Insert(i + 1, rightPart);
    }
    }
    }
    return rows;
    }

具体可参考:https://stackoverflow.com/questions/521146/c-sharp-split-string-but-keep-split-chars-separators

posted on 2019-08-15 21:24  NoMatterTryAgain  阅读(1916)  评论(0)    收藏  举报

导航