【发布时间】:2018-09-02 07:31:39
【问题描述】:
例如:
我有这个:
string commaSeparatedString = "124,45415,1212,4578,233,968,6865,32545,4545";
我想这样做为每 4 个找到逗号添加一个新行
124-45415-1212-4578
233-968-6865-32545
4545
【问题讨论】:
-
看看
string.Split(',')
例如:
我有这个:
string commaSeparatedString = "124,45415,1212,4578,233,968,6865,32545,4545";
我想这样做为每 4 个找到逗号添加一个新行
124-45415-1212-4578
233-968-6865-32545
4545
【问题讨论】:
string.Split(',')
这个呢:
string str = "124,45415,1212,4578,233,968,6865,32545,4545";
var result = string.Join("-", sss.Split(',').Select((c, index) => (index + 1) % 4 == 0 ?
c + Environment.NewLine : c));
别忘了先将LINQ 添加到您的 using 指令中:
using System.Linq;
【讨论】:
string.Join("", str.Split(',').Select((c, i) => (i != 0) && ((i + 1) % 4 == 0) ? c + Environment.NewLine : c + "-"))
试试这个:
const int batch = 4;
var target = "124,45415,1212,4578,233,968,6865,32545,4545";
var items = target.Split(',');
var results = new List<string>();
var continue = false;
var step = 0;
do
{
var slide = items.Skip(step++ * batch).Take(batch);
continue = slide.Count() == batch;
results.Add(string.Join('-', slide));
}while(continue);
【讨论】:
给你:
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.Write(SplitOnChar("124,45415,1212,4578,233,968,6865,32545,4545",',',4));
Console.ReadKey();
}
private static string SplitOnChar(string input, char theChar, int number)
{
string result = "";
int seen = 0;
int lastSplitIndex = 0;
for(int i = 0; i< input.Length;i++)
{
char c = input[i];
if (c.Equals(theChar))
{
seen++;
if (seen == number)
{
result += input.Substring(lastSplitIndex + 1, i - lastSplitIndex -1);
result += Environment.NewLine;
lastSplitIndex = i;
seen = 0;
}
}
}
result += input.Substring(lastSplitIndex + 1);
result = result.Replace(theChar, '-');
return result;
}
}
}
【讨论】: