如何在第n次出现时拆分字符串?

时间:2013-04-16 10:33:21

标签: c#

我想要做的是分割第n个字符串(在这种情况下是“\ t”)。这是我正在使用的代码,它会在每次出现“\ t”时分割。

string[] items = input.Split(new char[] {'\t'}, StringSplitOptions.RemoveEmptyEntries);

如果input =“one \ ttwo \ tthree \ tfour”,我的代码将返回以下数组:

  • 一个
  • 2
  • 3
  • 4

但是,假设我想在第二个“\ t”之后将它分成每个“\ t”。所以,它应该返回:

  • 一二
  • 3
  • 4

4 个答案:

答案 0 :(得分:16)

内置任何东西。

您可以使用现有的Split,使用TakeSkipstring.Join重建您原来拥有的部分。

string[] items = input.Split(new char[] {'\t'}, 
                             StringSplitOptions.RemoveEmptyEntries);
string firstPart = string.Join("\t", items.Take(nthOccurrence));
string secondPart = string.Join("\t", items.Skip(nthOccurrence))

string[] everythingSplitAfterNthOccurence = items.Skip(nthOccurrence).ToArray();

另一种方法是遍历字符串中的所有字符,找到第n个匹配项的索引和它之前和之后的子字符串(或者在第n个之后找到下一个索引,在该字符串上找到子字符串......等等...等...)。

答案 1 :(得分:4)

[编辑]重新阅读已编辑的OP后,我意识到这不会做现在的问题。这会在每个第n个目标上分裂; OP希望在第n个之后拆分每个目标。

无论如何,我会把这个留给后人。


如果您使用MoreLinq extensions,则可以利用其Batch方法。

您的代码将如下所示:

string text = "1\t2\t3\t4\t5\t6\t7\t8\t9\t10\t11\t12\t13\t14\t15\t16\t17";

var splits = text.Split('\t').Batch(5);

foreach (var split in splits)
    Console.WriteLine(string.Join("", split));

我可能只是使用Oded的实现,但我想我会发布这个替代方法。

Batch()的实现如下:

public static class EnumerableExt
{
    public static IEnumerable<IEnumerable<TSource>> Batch<TSource>(this IEnumerable<TSource> source, int size)
    {
        TSource[] bucket = null;
        var count = 0;

        foreach (var item in source)
        {
            if (bucket == null)
                bucket = new TSource[size];

            bucket[count++] = item;

            if (count != size)
                continue;

            yield return bucket;

            bucket = null;
            count = 0;
        }

        if (bucket != null && count > 0)
            yield return bucket.Take(count);
    }
}

答案 2 :(得分:1)

您可能需要拆分并重新组合。像

这样的东西
int tabIndexToRemove = 3;
string str = "My\tstring\twith\tloads\tof\ttabs";
string[] strArr = str.Split('\t');
int numOfTabs = strArr.Length - 1;
if (tabIndexToRemove > numOfTabs)
    throw new IndexOutOfRangeException();
str = String.Empty;
for (int i = 0; i < strArr.Length; i++)
    str += i == tabIndexToRemove - 1 ? 
        strArr[i] : String.Format("{0}\t", strArr[i]);

结果:

  

我的字符串有大量标签

我希望这会有所帮助。

答案 3 :(得分:0)

// Return a substring of str upto but not including
// the nth occurence of substr
function getNth(str, substr, n) {
  var idx;
  var i = 0;
  var newstr = '';
  do {
    idx = s.indexOf(c);
    newstr += str.substring(0, idx);
    str = str.substring(idx+1);
  } while (++i < n && (newstr += substr))
  return newstr;
}
相关问题