如果长度为1,我需要帮助加入数组中的两个或多个连续项。
例如,我想改变这个:
string[] str = { "one", "two", "three","f","o","u","r" };
致:
str = {"one","two","three","four"};
答案 0 :(得分:4)
使用GroupAdjacent
扩展名(例如listed here),您可以执行以下操作:
string[] input = ...
string[] output = input.GroupAdjacent(item => item.Length == 1)
.SelectMany(group => group.Key
? new[] { string.Concat(group) }
: group.AsEnumerable())
.ToArray();
如果效率是一个很大的问题,我建议你自己编写迭代器块或类似的。
答案 1 :(得分:0)
这样的事情应该有效:
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();
}
答案 2 :(得分:0)
这是我的答案,用于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;
}
输出:
一个
2个
3个
4个
5
答案 3 :(得分:0)
我认为最简单,最有效的方法就是迭代数组:
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());
答案 4 :(得分:0)
你可以这样做:
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++]);
}
}