简体   繁体   English

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

[英]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. 我能想到这样做的唯一方法是循环文本以找到X字符之前的最后一个空格(如果x不是空格),拆分字符串。 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 . 在此处阅读有关迭代器块和yield return构造的更多信息 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: 然后,可以像普通的Split方法一样调用它:

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). 迭代器块的一个好处是它们允许您在返回元素后执行逻辑(在yield return语句之后的逻辑)。 This allows the programmer to write the logic the way he or she is probably thinking about the problem. 这允许程序员以他或她可能正在考虑问题的方式编写逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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