| |
| Posted by AEon | PermalinkReply |
|
AEon
| Parsing game log files I noted that the below function was missing in std.string.
Imagine a string with several occurrences of a char, e.g. ':'. Now to get the first offset you could use find(str,":"), but what about any other occurrences? A new find command:
int find(char[] s, char[] sub, int count)
could let you e.g. search for the second occurrence, via
int pos = find(str, ":", 2 )
that would also have the advantage, that you can search for one or *many* characters.
For the special case of searching for just 1 char I did this:
int[] l=locate("moo:blah:oink:foo", ':');
^ ^ ^
0123456789012345678
111111111
-> returns l[0] = 3, l[1] = 8, l[2] = 13 -> l.length=3
And this is the code I used:
<code>
//---Locate the array positions of one char search---
//
// Char: Character you want to locate.
//
// return: Array of offsets that were found.
// If not found [0] = -1
//
int[] locate( char[] string, char Char )
{
int[] pos;
pos.length == 0; // Init size
foreach(int i, char Ch; string)
{
if( Ch == Char )
pos ~= i; // Collect "hits"
}
// ***Possibly return array of length 0 as invalid check?
if( pos.length == 0 )
pos ~= -1; // Nothing found, first element -1
return pos;
}
</code>
Maybe it would be nice to have this in std.string?
A more powerful version:
int[] locate( char[] string, char[] sub )
might then be even better.
AEon
|