String to StringArray

Didn’t find functions in JUCE for getting StringArray from String. Made my own.

    File infile ( "/home/user/text.txt" );
    if ( infile.existsAsFile() ) {

        String buffer = infile.loadFileAsString();
        
        // string to string array (enter is line end)
        StringArray strAry;
        int j = 0;
        for ( int i = 0; i < buffer.length(); i++ ) {
            String tmp = "";
            while ( buffer[i] != 13 && buffer[i] != 10 && i < buffer.length() ) {
                tmp += buffer[i];
                i++;
            }
            if ( buffer[i] == 13 ) i++; // Windows enter '13 10' compensation
            strAry.set ( j, tmp );
            j++;
        }
        // result in strAry
    }

There’s juce::StringArray::fromTokens():

https://docs.juce.com/master/classStringArray.html#a2996bff706bcf449fbdab264c266307a

https://docs.juce.com/master/classStringArray.html#a054a8f035e17076b2f1428995517fc2d

Or juce::StringArray::fromLines():

https://docs.juce.com/master/classStringArray.html#aa65070cc0eda93b9ebb7da2b1325781b

1 Like

Thanks! It is not immediately clear. Here’s an example.

    File infile ( "/home/user/text.txt" );
    if ( infile.existsAsFile() ) {

        String buffer = infile.loadFileAsString();
        
        // string to string array
        StringArray strAry;
        strAry = StringArray::fromLines ( buffer );
        
        // result in strAry
    }

I’d probably wrap this functionality in a free function:

juce::StringArray readLinesFromFile (juce::File file)
{
    jassert (file.existsAsFile());
    return juce::StringArray::fromLines (file.loadFileAsString());
}

const auto strAry = readLinesFromFile ({"/home/user/text.txt"});
2 Likes