我想将以下字符串拆分为三个元素:
first, middle, middle, middle, middle, last
结果将是:
splits[0] = "first"
splits[1] = "middle, middle, middle, middle"
splits[2] = "last"
我不知道这是否最好用正则表达式或字符串方法完成。
答案 0 :(得分:7)
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)
};
我认为第二种解决方案更清晰,更易于理解。但它的缺点是第一个和最后一个逗号必须后跟一个空格。第一个版本不存在此要求。
答案 1 :(得分:1)
这个怎么样
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();
输出[0] =“第一”
输出[1] =“中,中,中,中”
输出[2] =“最后”
选择(...修剪())会删除拆分后的前导空格。
GroupBy(...)提供三个列表({“first”},{“middle”,“middle”,“middle”,“middle”},{“last”}
选择(...加入(...))会使用正确的逗号创建最终字符串。
hth,
艾伦。
答案 2 :(得分:0)
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);
答案 3 :(得分:0)
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();