Get indexes of character in array

2012-03-27 Thread Andrej Mitrovic
I'd like to get a list of indexes into an array that matches a character. E.g.:

"a foo a bar a".indexes("a") == [0, 6, 12]

Anything like that in Phobos?


Re: Get indexes of character in array

2012-03-27 Thread Andrej Mitrovic
> 3/28/12, Andrej Mitrovic  wrote:
> I'd like to get a list of indexes into an array that matches a character.
> E.g.:
>
> "a foo a bar a".indexes("a") == [0, 6, 12]

Hah I even managed to screw up that "bar" has an 'a' there. Anywho
this works just fine:

size_t[] indexes(string input, dchar target)
{
size_t[] result;
foreach (index, dchar ch; input)
{
if (ch == target)
result ~= index;
}
return result;
}

The cool thing about the foreach loop is that 'index' will point to
the exact code point of the target (it won't just be incremented by +1
on each loop).


Re: Get indexes of character in array

2012-03-27 Thread Andrej Mitrovic
On 3/28/12, Andrej Mitrovic  wrote:
> snip

Also a better name might be 'indices'.


Re: Get indexes of character in array

2012-03-27 Thread James Miller
On 28 March 2012 19:35, Andrej Mitrovic  wrote:
> I'd like to get a list of indexes into an array that matches a character. 
> E.g.:
>
> "a foo a bar a".indexes("a") == [0, 6, 12]
>
> Anything like that in Phobos?

std.regex might be able to produce something like it.

--
James Miller


Re: Get indexes of character in array

2012-03-28 Thread Dmitry Olshansky

On 28.03.2012 10:42, Andrej Mitrovic wrote:

3/28/12, Andrej Mitrovic  wrote:
I'd like to get a list of indexes into an array that matches a character.
E.g.:

"a foo a bar a".indexes("a") == [0, 6, 12]


Hah I even managed to screw up that "bar" has an 'a' there. Anywho
this works just fine:

size_t[] indexes(string input, dchar target)
{
 size_t[] result;
 foreach (index, dchar ch; input)
 {
 if (ch == target)
 result ~= index;
 }
 return result;
}

The cool thing about the foreach loop is that 'index' will point to
the exact code point of the target (it won't just be incremented by +1
on each loop).


Piece of cake indeed.
Just use Appender + put for building arrays in future,  it's becoming 
military grade soon:

 https://github.com/D-Programming-Language/phobos/pull/502

--
Dmitry Olshansky