簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM