简体   繁体   中英

Split string after x characters and whitespace

having a bit of a brain melt here and could do with some help on the logic for solving this issue.

im basically going to be creating images that are just text based on a user input.

Image width is fixed, so i need to parse the text so it all fits on the image, but i need to make sure that i only split on a whitespace and not break up words.

like this

after X amount of characters split string on last whitespace.
then after the next X amount of characters repeat.

The only way i can think of doing this is by looping through the text to find the last whitepace before X characters (if x is not a whitespace), splitting the string. and then repeating.

Can anyone think of a more elegant solution or is this probably the best way?

A loop is certainly the way to go. The algorithm you describe should work fine. This can be done quite elegantly using an iterator block. Read more about iterator blocks and the yield return construct here . You could also make the method into an extension method so that it would look something like this:

public static IEnumerable<string> NewSplit(this string @this, int lineLength) {
    var currentString = string.Empty;
    var currentWord = string.Empty;

    foreach(var c in @this)
    {
        if (char.IsWhiteSpace(c))
        {
            if(currentString.Length + currentWord.Length > lineLength)
            {
                yield return currentString;
                currentString = string.Empty;
            }
            currentString += c + currentWord;
            currentWord = string.Empty;
            continue;
        }
        currentWord += c;
    };
    // The loop might have exited without flushing the last string and word
    yield return currentString; 
    yield return currentWord;
}

Then, this can be invoked like the normal Split method:

myString.NewSplit(10);

One of the benefits of iterator blocks is that they allow you to perform logic after an element is returned (the logic right after the yield return statements). This allows the programmer to write the logic the way he or she is probably thinking about the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM