Efficiency of String concatenation vs getting a substring

I am trying to understand a basic concept for efficiency. I am creating a class to iterate through String and return substrings.

String StringIterator::consumeToChar(const juce_wchar& c)
{    
    mem.clear();
    while (!atEnd() && *this != c) mem += inc(); // checks if CharPointer_UTF8's 
    return mem;                           //current character matches given char        
}

This code increments a CharPointer_UTF8 and adds characters to String mem as it increments, so I can save the result as a substring. It seems like this would be inefficient.

Would it be more efficient to have two iterators, one that saves the state before incrementing the CharPointer_UTF8 and (instead of concatenating to String with +=) get a substring with the two CharPointer_UTF8? Actually, I don’t even know how to do that, so if you could write a code example, it would be helpful!

Essentially my question is: What’s the most efficient way to get a substring from String? And what is the syntax?

Ah figured it out:

String(pointer_a, pointer_b)

“String” as in the actual class String, not a string object.

I’m assuming this is more efficient than +=

1 Like

Yes, vastly more efficient!