[英]need help in joining items in an array c#
如果长度为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();
如果效率是这里的重点,我建议您滚动自己的迭代器块或类似的块。
这样的事情应该起作用:
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();
}
这是我的答案,用在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;
}
输出:
一
二
三
四
五
我认为最简单,最有效的方法是遍历数组:
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());
你可以这样做:
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++]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.