在x个字符和空格之后拆分字符串

时间:2013-06-15 15:29:46

标签: c# string loops

这里有一点大脑融化,可以帮助解决这个问题的逻辑。

我基本上将根据用户输入创建只是文本的图像。

图像宽度是固定的,所以我需要解析文本,使其全部适合图像,但我需要确保我只拆分空白而不分解文字。

像这样

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

我能想到这样做的唯一方法是循环遍历文本以找到X字符之前的最后一个空格(如果x不是空格),拆分字符串。然后重复。

有人能想到更优雅的解决方案,还是这可能是最好的方法?

1 个答案:

答案 0 :(得分:3)

循环肯定是要走的路。您描述的算法应该可以正常工作。使用迭代器块可以非常优雅地完成此操作。阅读有关迭代器块和yield return构造here的更多信息。你也可以把方法变成extension method,这样看起来像这样:

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语句之后的逻辑)。这允许程序员以他或她可能正在考虑问题的方式编写逻辑。

相关问题