Thread overview
New feature for std.string suggestion: locate()
Mar 31, 2005
AEon
Mar 31, 2005
Regan Heath
Mar 31, 2005
AEon
March 31, 2005
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


March 31, 2005
On Thu, 31 Mar 2005 04:09:35 +0200, AEon <aeon2001@lycos.de> wrote:
> 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?

You could use a slice, i.e.

i = find(str,':');
j = i + 1 + find(str[i+1..$],':');

Regan
March 31, 2005
Regan Heath wrote:
> On Thu, 31 Mar 2005 04:09:35 +0200, AEon <aeon2001@lycos.de> wrote:
> 
>> 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?
> 
> 
> You could use a slice, i.e.
> 
> i = find(str,':');
> j = i + 1 + find(str[i+1..$],':');

That very much reminds me of the evil pointer arithmetic one used to see everywhere in C :)

AEon