簡體   English   中英

在空格處拆分長串

[英]Split long string at the spaces

在我的程序中,如果它太長,我需要將一個字符串拆分成多行。 現在我正在使用這種方法:

private List<string> SliceString(string stringtocut)
{
    List<string> parts = new List<string>();
    int i = 0;
    do
    {  
        parts.Add(stringtocut.Substring(i, System.Math.Min(18, stringtocut.Substring(i).Length)));
        i += 18;
    } while (i < stringtocut.Length);
    return parts;
}

唯一的問題是,如果第19個字符不是空格,我們會將一個字縮小一半,看起來非常糟糕。

例如

字符串:這是一個超過18個字母的長信號。

Sliced string: 
This is a long sent
ance with more than
 18 letters.

我如何剪切字符串,使其每個部分不超過18個字符,但如果可以,請返回最近的空格? 我已經習慣了上面的算法,但我似乎無法得到它。

謝謝!

也許使用這樣的正則表達式:

var input = "This is a long sentence with more than 18 letters.";
var output = Regex.Split(input, @"(.{1,18})(?:\s|$)")
                  .Where(x => x.Length > 0)
                  .ToList();

返回結果:

[ "This is a long", "sentence with more", "than 18 letters." ]

更新

這是一個類似的解決方案來處理很長的單詞(雖然我覺得它不會表現得那么好,所以你可能想要對此進行基准測試):

var input = "This is a long sentence with a reallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreally long word in it.";
var output = Regex.Split(input, @"(.{1,18})(?:\s|$)|(.{18})")
                  .Where(x => x.Length > 0)
                  .ToList();

這會產生結果:

[ "This is a long", 
  "sentence with a", 
  "reallyreallyreally", 
  "reallyreallyreally", 
  "reallyreallyreally", 
  "reallyreallyreally", 
  "really long word", 
  "in it." ]

這實際上並不是優化也不是優雅的代碼,而是給出了理想的結果。 重構應該相對容易:

string longSentence = "This is a long sentence with more than 18 letters.";

List<string> words = new List<string>();
string currentSentence = string.Empty;

var parts = longSentence.Split(' ');
foreach (var part in parts)
{
    if ((currentSentence + " " + part).Length < 18)
    {
        currentSentence += " " + part;
    }
    else
    {
        words.Add(currentSentence);
        currentSentence = part;
    }
}
words.Add(currentSentence);
words[0] = words[0].TrimStart();

結果:

This is a long
sentence with
more than 18
letters.

基本上你添加每個單詞直到你要打破18個字母。 此時,您保存零件並重新開始。 當它結束時,你加上剩下的東西。 此外,在開始時需要一些不必要的空間需要一些修剪。

試試這段代碼:

int len = 0;
int index = 0;
text = string.Join(Environment.NewLine,
                   text.SplitBy(' ')
                       .GroupBy(w =>
                                { 
                                    if (len + w.Length > 18)
                                    {
                                        len = 0;
                                        index++;
                                    }
                                    len += w.Length + 1;
                                    return index;
                                })
                       .Select(line => string.Join(" ", line)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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