counting characters

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 19 02:55:43 PDT 2016


On Tuesday, July 19, 2016 09:41:32 John via Digitalmars-d-learn wrote:
> On Tuesday, 19 July 2016 at 09:34:11 UTC, celavek wrote:
> > Hi,
> >
> > I am trying to count characters in a string like:
> >
> > const string dna_chain =
> > "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC";
> > counts['A'] = countchars!(dna_chain, 'A');
>
> countchars(dna_chain, "A");

That fixes the call to countchars, but given that the OP is only looking to
count a specific character and is not really using a "pattern" (which is
what countchars looks for), it's bound to be more efficient to just use a
function which counts the number of elements in the array which match a
certain character rather than seaching for a pattern. std.algorithm.count
would be the most idiomatic choice. So, you get something like

auto result = count(dna_chain, 'A');

or if you know that the string is always going to just contain ASCII (as
seems likely based on the example), then string.representation can be used
to convert the string to immutable(ubyte)[] in order to avoid the
auto-decoding that occurs with string and range-based functions. e.g.

auto result = count(dna_chain.representation, 'A');

That's almost certainly the fastest way to do it with Phobos.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list