[英]How to merge short strings in a list into long strings
這里我有一個字符串列表如下:
List<string> str = new List<string>
{ "1", "22", "3", "44", "55", "666666", "7777777", "8", "99" };
我想要的是將短字符串合並為長度小於 n 的長字符串。
預計:
n = 5
newlist = { "1223", "4455", "666666", "7777777", "899" };
void Main()
{
List<string> str = new() { "1", "22", "3", "44", "55", "666666", "7777777", "8", "99" };
const int n = 5;
List<string> newList = new();
var newString = string.Empty;
foreach (var s in str)
{
if ((newString.Length + s.Length) <= n)
{
newString += s;
continue;
}
newList.Add(newString);
newString = s;
}
newList.Add(newString); // Don't forget the last under length string
Console.WriteLine(newList);
}
// Outputs "1223", "4455", "666666", "7777777", "899"
// Also handles empty input strings
遲到的答案。 LINQ .Aggregate()
是foreach
循環的替代解決方案。
.Aggregate()
能夠用於迭代當前值和下一個值。
檢查toBeAppended
值。
1.1 如果toBeAppended.Length
> n
,則將current
值添加到result
中。 並且您需要重置current
值。
1.2 Else 用toBeAppended
設置current
。
交互結束后,確保您需要將最后一個值添加到result
中。
List<string> str = new List<string> { "1", "22", "3", "44", "55", "666666", "7777777", "8", "99" };
int n = 5;
var result = new List<string>();
var last = str.Aggregate("",
(current, next) =>
{
var toBeAppended = current + next;
if (toBeAppended.Length >= n)
{
result.Add(current);
current = next;
}
else
{
current = toBeAppended;
}
return current;
});
result.Add(last);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.