[英]Split string after x characters and whitespace
这里有一点大脑融化,可以帮助解决这个问题的逻辑。
我基本上将创建基于用户输入的文本图像。
图像宽度是固定的,所以我需要解析文本,使其全部适合图像,但我需要确保我只拆分空白而不分词。
像这样
after X amount of characters split string on last whitespace.
then after the next X amount of characters repeat.
我能想到这样做的唯一方法是循环文本以找到X字符之前的最后一个空格(如果x不是空格),拆分字符串。 然后重复。
谁能想到更优雅的解决方案,还是这可能是最好的方法?
循环肯定是要走的路。 您描述的算法应该可以正常工作。 使用迭代器块可以非常优雅地完成此操作。 在此处阅读有关迭代器块和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
语句之后的逻辑)。 这允许程序员以他或她可能正在考虑问题的方式编写逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.