.indexOf for multiple results

后端 未结 4 738
礼貌的吻别
礼貌的吻别 2021-01-06 03:05

Let\'s say I have a text and I want to locate the positions of each comma. The string, a shorter version, would look like this:

string s = \"A lot, of text,          


        
相关标签:
4条回答
  • 2021-01-06 03:14

    IndexOf also allows you to add another parameter for where to start looking. You can set that parameter to be the last known comma location +1. For example:

    string s = "A lot, of text, with commas, here and, there";
    int loc = s.IndexOf(',');
    while (loc != -1) {
        Console.WriteLine(loc);
        loc = s.IndexOf(',', loc + 1);
    }
    
    0 讨论(0)
  • 2021-01-06 03:14

    You could use the overload of the IndexOf method that also takes a start index to get the following comma, but you would still have to do that in a loop, and it would perform pretty much the same as the code that you have.

    You could use a regular expression to find all commas, but that produces quite some overhead, so that's not more optimised than what you have.

    You could write a LINQ query to do it in a different way, but that also has some overhead so it's not more optimised than what you have.

    So, there are many alternative ways, but not any way that is more optimised.

    0 讨论(0)
  • 2021-01-06 03:19

    You could use Regex.Matches(string, string) method. This will return a MatchCollection and then you could determine the Match.Index. MSDN has a good example,

    using System; using System.Text.RegularExpressions;

    public class Example
    {
       public static void Main()
       {
          string pattern = @"\b\w+es\b";
          string sentence = "Who writes these notes?";
    
          foreach (Match match in Regex.Matches(sentence, pattern))
             Console.WriteLine("Found '{0}' at position {1}", 
                               match.Value, match.Index);
       }
    }
    // The example displays the following output:
    //       Found 'writes' at position 4
    //       Found 'notes' at position 17
    
    0 讨论(0)
  • 2021-01-06 03:30

    Here I got a extension method for that, for the same use as IndexOf:

    public static IEnumerable<int> AllIndexesOf(this string str, string searchstring)
    {
        int minIndex = str.IndexOf(searchstring);
        while (minIndex != -1)
        {
            yield return minIndex;
            minIndex = str.IndexOf(searchstring, minIndex + searchstring.Length);
        }
    }
    

    so you can use

    s.AllIndexesOf(","); // 5    14    27    37
    

    https://dotnetfiddle.net/DZdQ0L

    0 讨论(0)
提交回复
热议问题