[英]need help in joining items in an array c#
I need help in joining two or more consecutive items in array if their length is 1. 如果长度为1,我需要帮助将两个或多个连续的项目加入数组。
For example, I want to change this : 例如,我要更改此:
string[] str = { "one", "two", "three","f","o","u","r" };
To : 至 :
str = {"one","two","three","four"};
Using a GroupAdjacent
extension (such as the one listed here ), you can do something like this : 使用
GroupAdjacent
扩展名(例如此处列出的扩展名),您可以执行以下操作:
string[] input = ...
string[] output = input.GroupAdjacent(item => item.Length == 1)
.SelectMany(group => group.Key
? new[] { string.Concat(group) }
: group.AsEnumerable())
.ToArray();
If efficiency is a big concern here, I suggest rolling your own iterator block or similar. 如果效率是这里的重点,我建议您滚动自己的迭代器块或类似的块。
Something like this should work: 这样的事情应该起作用:
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();
}
This is my answer, used in LINQPad :) 这是我的答案,用在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;
}
Output: 输出:
one
一
two二
three三
four四
five五
I think the easiest and more efficient way is just iterating over the array: 我认为最简单,最有效的方法是遍历数组:
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());
You can do this: 你可以这样做:
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.