分“首先,中间,中间,last"进入有3个元素的数组(第一,中间,最后)
本文关键字:中间 元素 3个 数组 第一 最后 last 首先 quot | 更新日期: 2023-09-27 18:18:01
我想把下面的字符串分成三个元素:
first, middle, middle, middle, middle, last
所以结果是:
splits[0] = "first"
splits[1] = "middle, middle, middle, middle"
splits[2] = "last"
我不知道这是最好的regex或字符串方法。
var s = "first, middle, middle, middle, middle, last";
var singleItems = s.Split(',').Select(x => x.Trim());
var splits = new []
{
singleItems.Take(1).Single(),
singleItems.Skip(1).Take(singleItems.Count() - 2)
.Aggregate("", (s1, s2) => s1 + s2 + ", ")
.Trim(' ', ','),
singleItems.Skip(singleItems.Count() - 1).Single()
};
另一种方法是:
var firstIndex = s.IndexOf(',');
var lastIndex = s.LastIndexOf(',');
var splits = new []
{
s.Substring(0, firstIndex),
s.Substring(firstIndex + 2, lastIndex - (firstIndex + 2)),
s.Substring(lastIndex + 2)
};
我认为第二个解决方案更清晰,更容易理解。但它的缺点是,第一个和最后一个逗号必须后跟一个空格。第一个版本不存在此要求。
这个怎么样
var input = "first, middle, middle, middle, middle, last";
var outputs = input.Split(',').Select(wrd=>wrd.Trim())
.GroupBy(wrd=>wrd)
.Select(lst => string.Join(", ", lst)).ToArray();
output[0] = "first"
输出[1]= "middle, middle, middle, middle"
[2] = "last"
Select(…Trim())删除分割后的前导空格。
GroupBy(…)提供三个列表({"第一"},{"中产"、"中间"、"中间"、"中间"},{"最后"}
Select(…Join(…))用正确的逗号创建最终字符串。
hth,
艾伦。
string separator = ", ";
string input = "first, middle, middle, middle, middle, last";
int i1 = input.IndexOf(separator);
int i2 = input.LastIndexOf(separator);
string[] splits = new string[3];
splits[0] = input.Substring(0, i1);
splits[1] = input.Substring(i1 + separator.Length, i2 - i1 - separator.Length);
splits[2] = input.Substring(i2 + separator.Length);
string data = "first, middle, middle, middle, middle, last";
string[] splitData = data.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
Dictionary<string, string> splits = new Dictionary<string, string>();
foreach (var s in splitData)
{
var temp = s.Trim();
if (splits.ContainsKey(temp))
{
splits[temp] += ", " + temp;
}
else
{
splits[temp] = temp;
}
}
string[] result = splits.Select(y => y.Value).ToArray();