我有这样的字符串(包括换行符)
A2,
10.22,
-57,
A,
10.23,
-68,
A2,
10.24,
-60,
LB,
10.25,
-62,
我试图让这个字符串看起来像这样:
A2,10.22,-57,
A,10.23,-68,
A2,10.24,-60,
LB,10.25,-62,
我需要在我尝试的每3行中加入字符串:
int numLines = a.Split('\n').Length;
for (int i = 0; i < numLines; i += 3)
{
richTextBox1.Text = a.Replace("\n", "");
}
但它不适合我。请帮帮我
答案 0 :(得分:3)
您也可以使用LINQ来解决这个问题,方法是使用index overload of .Select
来保留行号的运行计数,然后将它们分组为3组 - 我使用的整数除法为{{ 1}}行索引,一次3个,但可能还有其他合适的方式。
Floor
上述组中的每件商品均为var groups = values.Select((s, idx) => (Index: idx / 3, Value: s))
.GroupBy(x => x.Index);
。
您还需要警惕newlines - 这些可能是IEnumerable<(Index, Value)>
在Windows中,而不仅仅是您所指示的\r\n
。
以下是一个例子:
\n
由于您已经在每个字符串的末尾(包括最后一个字符串)都有逗号,因此无需添加其他分隔符。
输出:
var a =
@"A2,
10.22,
-57,
A,
10.23,
-68,
A2,
10.24,
-60,
LB,
10.25,
-62,";
var values = a.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
var groups = values.Select((s, idx) => (Index: idx / 3, Value: s))
.GroupBy(x => x.Index);
foreach (var grp in groups)
{
Console.WriteLine(string.Join("", grp.Select(x => x.Value)));
}
答案 1 :(得分:2)
为什么不使用split给你的数组?
var newArr = a.Split('\n');
for (int i = 0; i < newArr.Length; i += 3)
{
richTextBox1.Text = newArr[i] + newArr[i + 1] + newArr[i + 2];
}
不要忘记检查数组的长度,这样就不会得到IndexOutOfRange异常。
答案 2 :(得分:1)
尝试使用Aggregate
功能
var outPutList = data.Replace("\r", string.Empty).Replace("\n", string.Empty).Split(",").Aggregate(new StringBuilder(""), (x, y) =>
{
if (double.TryParse(y, out double parsedValue))
x.Append(" " + parsedValue);
else
{
x.Append(Environment.NewLine);
x.Append(y.Trim());
}
return x;
});
richTextBox1.Text = outPutList.ToString();
这是输出
答案 3 :(得分:1)
static void Main(string[] args)
{
var Lines = System.IO.File.ReadAllLines("input.txt");
var Result = new StringBuilder();
var SB = new StringBuilder();
for (var i = 0; i < Lines.Length; i++)
{
SB.Append(Lines[i]);
if ((i+1) % 3 == 0)
{
Result.Append($"{SB.ToString()}{Environment.NewLine}");
SB.Clear();
}
}
System.IO.File.WriteAllText("output.txt", Result.ToString());
}
答案 4 :(得分:1)
我假设输入实际来自这里的文件。
<connectionStrings>
<add name="MyConnectionString" connectionString="server=192.168.11.11;database=Test;uid=someusername; pwd=somepassword" providerName="System.Data.SqlClient" />
</connectionStrings>
答案 5 :(得分:0)
尝试此解决方案,它是
和linq
循环
for
答案 6 :(得分:-1)
试试这个
var arr = [{ "symbol": "CAT", "market_a": "20" }, { "symbol": "DOG", "market_a": "40" }, { "symbol": "DUCK", "market_a": "15" }, { "symbol": "CAT", "market_b": "60" }, { "symbol": "DOG", "market_b": "55" }, { "symbol": "FISH", "market_b": "40" }, { "symbol": "CAT", "market_c": "65" }, { "symbol": "DOG", "market_c": "20" }, { "symbol": "fISH", "market_c": "70" }];
// Reduce your array into an object with key being symbol and value being the object required
var map = arr.reduce((a,{symbol, ...obj}) => {
a[symbol] = a[symbol] || {symbol};
Object.assign(a[symbol], obj); // append the remaining properties
return a;
}, {});
console.log(Object.values(map));
希望它可以帮到你