目前我需要一个关于我的问题的简单概念,因为我的最后一个想法是废话* t。 我有一个List的字符串,其中包含一些字符串数。
1.0, 1.1, 2.0, ..., 10.1, 10.2, 10.2.1, ...
现在我想在第一个数字被更改之前将/ n放入字符串中以换行新行。新行应该在逗号之前设置。
例如:
1.0, 1.1\n, 2.0\n, 3.0, ..., 5.0, 5.1\n, 6.0, ..., 10.1, 10.2, 10.2.1, ...
你知道一种更好,更有效的方法吗?
问候,C
答案 0 :(得分:1)
为了好玩....
string input = "1.0, 1.1, 2.0, 2.1, 2.5, 3.0, 3.7, 4.5, 4.6, 4.7, 5.9, 6.2, 6.7, 7.1, 7.2, 7.3, 7.4, 8.7, 8.8, 10.1, 10.2, 10.2.1, 10.2.3";
// Split at comma
var temp = input.Split(',').Select(x => x.Trim());
// Creates an IEnumerable with the strings grouped for their initial value
var result = Enumerable.Range(1, 10)
.Select(x => string.Join(",",
temp.Where(c => c.StartsWith(x.ToString() + "."))));
// Rejoin the strings in a single string excluding empty ones
string final = string.Join(Environment.NewLine + "," ,
result.Where(x => !string.IsNullOrEmpty(x)));
Console.WriteLine(final);
答案 1 :(得分:1)
您可以检查(n % 1 == 0)
的整数,看看您的第一个数字是否会发生变化。
var input = "1.0, 1.1, 2.0, 10.1, 10.2, 10.2.1";
string result = string.Empty;
var temp = input.Split(','); //You can also trim here as @Steve did
foreach (var item in temp)
{
//cast it to double, then check if it's an integer
if ((double.Parse(item.Trim())) % 1 == 0)
{
//this is an integer, the first digit will be changed, put "\n"
result += "\n" + item;
}
else
{
//this is not an integer, continue as usual.
result += item;
}
}
//on this line the variable result is formatted the way you want.
Console.WriteLine(result);