0

I'm trying to create substrings from each index in a string using this helper method

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);
    }
}

And the way I am using it is like this

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

So I essentially want to grab each string between the indexes in two.

So the subscring between index 0 and 9 and 13 and 19.

I'm just not sure how to do this without using linq

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
JohnA
  • 564
  • 1
  • 5
  • 20
  • 1
    consider using a regex? – Daniel A. White Sep 06 '20 at 01:49
  • Trying to do this without linq and regex and just like a pure way if that makes any sense – JohnA Sep 06 '20 at 01:50
  • @VargaDev _Why?_ What's wrong with LINQ? – Sweeper Sep 06 '20 at 01:51
  • Nothing I love linq, but I just want to try to do this without any extensions like regex or linq – JohnA Sep 06 '20 at 01:51
  • So given a `List` and a input string, you want to return the substrings of that input, given the indexes are actual pairs in `List` ? – TheGeneral Sep 06 '20 at 02:07
  • 1
    I do not understand where “substrings” are used here. The awkward loop simply returns the “index” of the character that matches `value`. What “substrings” are you trying to obtain from `str`? This comment… _”So I essentially want to grab each string between the indexes in two.”_ … makes no sense. – JohnG Sep 06 '20 at 02:25

1 Answers1

2

If I understand the problem, you just need to jump 2 in a for loop

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]);
}

or if you don't want to use an iterator method

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;
}

Usage

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

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

Output

2abcdef, 2abcdefgh

Full Demo Here

TheGeneral
  • 79,002
  • 9
  • 103
  • 141