A better way to write this function? (style question)

Thomas Gann thomasleegann at gmail.com
Mon Dec 30 13:40:57 PST 2013


I've written a Markov bot in D, and I have function whose job it 
is to take an input string, convert all newline characters to 
spaces and all uppercase letters to lowercase, and then return an 
array of words that are generated by splitting the string up by 
whitespace. Here is the function is question:

string[] split_sentence(string input)
{
     string line;

     foreach(c; input)
     {
         if(c == '\n' || c == '\r')
             line ~= ' ';

         else
             line ~= c.toLower();
     }

     return line.splitter(' ').filter!(a => a.length).array;
}

Obviously, one issue is that because the string is immutable, I 
can't modify it directly, and so I actually build an entirely new 
string in place. I would have just made a mutable duplicate of 
the input and modify that, but then I would get errors returning, 
because it expects string[] and not char[][]. Is there a more 
elegant way to do what I'm doing?


More information about the Digitalmars-d-learn mailing list