[英]Split string with Pipe for a chunk in simplest way?
Got a string let say 有一个字符串说
string mystring = "A\nB\nC\nD\nE\nF\nG\n"
want to convert it with | 想要将其转换为| for chunk of 5 为5块
string Converted string ="ABCDE|FG"
Any one liner solution.. 任何一种内衬解决方案
I am going this way 我要这样
private void TweakInputLines(string InputData)
{
List<string> lstInput = new List<string>();
if (!string.IsNullOrEmpty(InputData))
{
lstInput = InputData.Split('\n').ToList();
if (lstInput.Count > 4)
{
}
}
}
General solution (preserving variable length lines): 通用解决方案(保留可变长度的线):
string input = "A\nBC\nDEF\nG\nH\nI\nJKL\nMN\nO\nP\nQR\nS";
string output = string.Join("|", input.Split('\n')
.Select((s, i) => new { s, i })
.GroupBy(p => p.i / 5)
.Select(g => string.Join("", g.Select(p => p.s))));
Output: 输出:
ABCDEFGH|IJKLMNOP|QRS
Update 更新资料
If you use .Net 3.5, then you need to add .ToArray()
calls in string.Join()
methods. 如果使用.Net 3.5,则需要在string.Join()
方法中添加.ToArray()
调用。
string input = "A\nBC\nDEF\nG\nH\nI\nJKL\nMN\nO\nP\nQR\nS";
string output = string.Join("|", input.Split('\n')
.Select((s, i) => new { s, i })
.GroupBy(p => p.i / 5)
.Select(g => string.Join("", g.Select(p => p.s).ToArray()))
.ToArray());
Update 2 更新2
Another option is to use slightly modified solution by @SriramSakthivel 另一个选择是使用@SriramSakthivel稍作修改的解决方案
string input = "A\nBC\nDEF\nG\nH\nI\nJKL\nMN\nO\nP\nQR\nS";
string output = Regex.Replace(input, @"((?:.*\n){4}.*)\n", "$1|").Replace("\n", "");
Simple code is 简单的代码是
private void TweakInputLines(string InputData)
{
List<string> lstInput = new List<string>();
var returnstring = "";
if (!string.IsNullOrEmpty(InputData))
{
lstInput = InputData.Split('\n').ToList();
if (lstInput.Count > 9999)
{
int counter = 0;
foreach (var eachcharitem in lstInput)
{
counter++;
returnstring = returnstring + eachcharitem;
if (counter == 5)
{
returnstring = returnstring + "|";
counter = 0;
}
}
}
}
}
Another solution with the use of Linq - its more or less a "one-liner": 使用Linq的另一种解决方案-或多或少是“单线”的:
string mystring = "A\nB\nC\nD\nE\nF\nG\n";
var str = mystring
.Select((value, index) => new { Index = index, Value = value }) // insert Index
.GroupBy(i => (int)(i.Index / 5)) // group by index / 5
.Select(value => String.Join("",value.Select(temp => temp.Value))) // create string out of grouped chars
.Aggregate((a,b) => a + "|" + b); // create one string out of splitted chars
// and join the "|"-string in between
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.