Home > other >  Get substring between indexes
Get substring between indexes

Time:08-24

I need to get all substring between indexes for a given larger string

 string MyString="Hi Hello World 1 today is august 22 2022,Hello World 2 today is august 23 2022,Hello World 3 today is august 24 2022";
 string stringToFind = "today";
   List<int> positions = new List<int>();
    int pos = 0;
    while ((pos < MyString.Length) && (pos = MyString.IndexOf(stringToFind, pos)) != -1)
    {
        positions.Add(pos);
        pos  = stringToFind.Length;
       
    }

    Console.WriteLine("{0} occurrences", positions.Count);
    foreach (var p in positions)
    {
       string amountString = MyString.Substring(p, p - 1);
       Console.WriteLine(amountString);
        Console.WriteLine(p);
    } 

I need to get the first substring as :today is august 22 2022 the second one as :today is august 23 2022 then today is august 24 2022 but When i try to get the substring using "substring" i'am getting an error.

 string amountString = MyString.Substring(p, p - 1);

CodePudding user response:

string amountString = MyString.Substring(p, stringToFind.Length);

CodePudding user response:

You also might want to use Regex to do this. It's much simpler.

string MyString = "Hi Hello World 1 today is august 22 2022,Hello World 2 today is august 23 2022,Hello World 3 today is august 24 2022";
string stringToFind = "today";

List<int> positions =
    Regex
        .Matches(MyString, Regex.Escape(stringToFind))
        .Select(x => x.Index)
        .ToList();

Console.WriteLine("{0} occurrences", positions.Count);

foreach (var p in positions)
{
    Console.WriteLine(p);
}

That gives me:

3 occurrences
17
55
93
  • Related