需要帮助来连接数组中的项
本文关键字:数组 连接 帮助 | 更新日期: 2023-09-27 18:02:12
我需要帮助连接数组中长度为1的两个或多个连续项。
例如,我想修改这个:
string[] str = { "one", "two", "three","f","o","u","r" };
:
str = {"one","two","three","four"};
使用GroupAdjacent
扩展名(例如这里列出的扩展名),您可以执行以下操作:
string[] input = ...
string[] output = input.GroupAdjacent(item => item.Length == 1)
.SelectMany(group => group.Key
? new[] { string.Concat(group) }
: group.AsEnumerable())
.ToArray();
如果效率是一个大问题,我建议滚动你自己的迭代器块或类似的
这是我的答案,在LINQPad中使用:)
void Main()
{
string[] str = { "one", "two", "three","f","o","u","r","five" };
string[] newStr = Algorithm(str).ToArray();
newStr.Dump();
}
public static IEnumerable<string> Algorithm(string[] str)
{
string text = null;
foreach(var item in str)
{
if(item.Length > 1)
{
if(text != null)
{
yield return text;
text = null;
}
yield return item;
}
else
text += item;
}
if(text != null)
yield return text;
}
输出:一个
两个
三
四
5
我认为最简单、最有效的方法就是遍历数组:
string[] str = { "one", "two", "three", "f", "o", "u", "r" };
List<string> output = new List<string>();
StringBuilder builder = null;
bool merge = false;
foreach(string item in str)
{
if (item.Length == 1)
{
if (!merge)
{
merge = true;
builder = new StringBuilder();
}
builder.Append(item);
}
else
{
if (merge)
output.Add(merge.ToString());
merge = false;
output.Add(item);
}
}
if (merge)
output.Add(builder.ToString());
应该这样做:
private string[] GetCombined(string[] str)
{
var combined = new List<string>();
var temp = new StringBuilder();
foreach (var s in str)
{
if (s.Length > 1)
{
if (temp.Length > 0)
{
combined.Add(temp.ToString());
temp = new StringBuilder();
}
combined.Add(s);
}
else
{
temp.Append(s);
}
}
if (temp.Length > 0)
{
combined.Add(temp.ToString());
temp = new StringBuilder();
}
return combined.ToArray();
}
你可以这样做:
string[] str = { "one", "two", "three", "f", "o", "u", "r" };
var result = new List<string>();
int i = 0;
while (i < str.Length) {
if (str[i].Length == 1) {
var sb = new StringBuilder(str[i++]);
while (i < str.Length && str[i].Length == 1) {
sb.Append(str[i++]);
}
result.Add(sb.ToString());
} else {
result.Add(str[i++]);
}
}