More efficient way to get all indexes of a character in a string

后端 未结 7 533
遇见更好的自我
遇见更好的自我 2020-12-04 01:41

Instead of looping through each character to see if it\'s the one you want then adding the index your on to a list like so:

     var foundIndexes = new List&         


        
7条回答
  •  隐瞒了意图╮
    2020-12-04 02:02

    If the string is short, it may be more efficient to search the string once and count up the number of times the character appears, then allocate an array of that size and search the string a second time, recording the indexes in the array. This will skip any list re-allocations.

    What it comes down to is how long the string is and how many times the character appears. If the string is long and the character appears few times, searching it once and appending indicies to a List will be faster. If the character appears many times, then searching the string twice (once to count, and once to fill an array) may be faster. Exactly where the tipping point is depends on many factors that can't be deduced from your question.

    If you need to search the string for multiple different characters and get a list of indexes for those characters separately, it may be faster to search through the string once and build a Dictionary> (or a List> using character offsets from \0 as the indicies into the outer array).

    Ultimately, you should benchmark your application to find bottlenecks. Often the code that we think will perform slowly is actually very fast, and we spend most of our time blocking on I/O or user input.

提交回复
热议问题