juce::String number of lines?

To get the number of lines contained in a juce::String i use something like:

static int getNumberOfLines (const juce::String& s)
{
    return juce::StringArray::fromLines (s).size();
}

Is there another approach (that avoids the allocations -if not mashed by the compiler-)?

(I mean without iterating myself through the internal representation).

Maybe a bit hacky, but could you just count the number of \n and +1?

1 Like

To be fair I think that would get you the same result as StringArray::fromLines(). It just breaks at \n and \r\n so I think counting \n seems reasonable, you’ll also need to return 0 if the string is empty.

I had a quick look to see if you could use std::count_if but I think we’re missing some iterator traits, so a simple for loop will likely suffice.

3 Likes

Yep ; counting \n ; i would have preferred to not iterate but it is seems i can not avoid to.

Thanks.

This is a cute approach, if you really need to find the absolute fastest count and want to put that CPU to use:

EDIT: and then, there is this, which I have to wonder if its any better, performance-wise, than the Daniel-Lemire code above:

juce::String juceStr = "Line 1\nLine 2\nLine 3\n"; // Example JUCE string
auto count = std::count_if(juceStr.toRawUTF8(), juceStr.toRawUTF8() + juceStr.length(),
                           [](char c) { return c == '\n'; });
1 Like

Funny that we have abstractions like juce::NewLine and juce::String (for UT8,16,32…) and that the only way to count new lines is to use explicitly both underlying type. :thinking:

Thanks anyway.

1 Like