1

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?

4

1 回答 1

3

循环肯定是要走的路。您描述的算法应该可以正常工作。这可以使用迭代器块非常优雅地完成。在此处阅读有关迭代器块和yield return构造的更多信息。您还可以将该方法设为扩展方法,使其看起来像这样:

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;
}

然后,可以像普通Split方法一样调用它:

myString.NewSplit(10);

迭代器块的好处之一是它们允许您在返回元素后执行逻辑(yield return语句之后的逻辑)。这允许程序员按照他或她可能考虑问题的方式编写逻辑。

于 2013-06-15T16:48:31.983 回答