【问题标题】:How do I take two at a time from a collection [duplicate]我如何从一个集合中一次取两个 [重复]
【发布时间】:2020-12-24 20:07:34
【问题描述】:

我正在尝试使用此辅助方法从字符串中的每个索引创建子字符串

public  List<int> AllIndexesOf(string str, string value)
{
    if (String.IsNullOrEmpty(value))
        throw new ArgumentException("the string to find may not be empty", "value");
    List<int> indexes = new List<int>();
    for (int index = 0; ; index += value.Length)
    {
        index = str.IndexOf(value, index);
        if (index == -1)
            return indexes;
        indexes.Add(index);
    }
}

而我的使用方式是这样的

string input = "27758585926302004842";
List<int> eh = AllIndexesOf(input, "2");

所以我基本上想在两个索引之间抓取每个字符串。

因此,索引 0 和 9 以及 13 和 19 之间的下标。

我只是不确定如何在不使用 linq 的情况下做到这一点

【问题讨论】:

  • 考虑使用正则表达式?
  • 尝试在没有 linq 和 regex 的情况下执行此操作,如果有意义的话,就像一种纯粹的方式
  • @VargaDev 为什么? LINQ 出了什么问题?
  • 我不喜欢 linq,但我只是想尝试在没有任何扩展如 regex 或 linq 的情况下做到这一点
  • 我不明白“子字符串”在哪里使用。笨拙的循环只是返回匹配value 的字符的“索引”。您想从str 获取哪些“子字符串”?这个评论……“所以我本质上想把索引之间的每个字符串一分为二。”……没有意义。

标签: c# .net


【解决方案1】:

如果我理解问题,你只需要在 for 循环中跳转 2

public static IEnumerable<string> GetSubStrings(string input, List<int> source)
{
   for (var i = 0; i < source.Count; i += 2)
      yield return input.Substring(source[i], source[i + 1] - source[i]);
}

或者如果你不想使用迭代器方法

public static List<string> GetSubStrings2(string input, List<int> source)
{
    var result = new List<string>();
    for (var i = 0; i < source.Count; i += 2)
      result.Add(input.Substring(source[i], source[i + 1] - source[i]));
    return result;
}

用法

var input = "2abcdef2ggg2abcdefgh2";
var indexes = AllIndexesOf(input, "2");

Console.WriteLine(string.Join(", ", GetSubStrings(input, indexes)));

输出

2abcdef, 2abcdefgh

Full Demo Here

【讨论】:

    猜你喜欢
    • 2021-10-23
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    相关资源
    最近更新 更多