1

I have a string like this (including newlines)

A2,
10.22,
-57,
A,
10.23,
-68,
A2,
10.24,
-60,
LB,
10.25,
-62,

I am trying to make this string to look like this:

 A2,10.22,-57,
 A,10.23,-68,
 A2,10.24,-60,
 LB,10.25,-62,

I need to join string in every 3 line i have tried :

int numLines = a.Split('\n').Length;
for (int i = 0; i < numLines; i += 3)
{
    richTextBox1.Text = a.Replace("\n", "");
}

But it is not working for me. Please help me out

StuartLC
  • 104,537
  • 17
  • 209
  • 285
Wuhu
  • 181
  • 1
  • 1
  • 11
  • 1
    I don't think that code is doing what you think it is. It reads that you just keep sending a replace "\n" with "" to the same control, as many times as that loop runs. Try send the individual pieces of text you want to a new string, and then replacing richTextBox1.Text once, at the end. – Phil S May 21 '18 at 12:29
  • Please, describe what exactly is not working. What did you get as a result? – default locale May 21 '18 at 12:36

7 Answers7

3

You can also approach this with LINQ, by using the index overload of .Select to retain a running count of the line numbers, and then to group them into groups of 3 - I've used integer division to Floor the line index, 3 at a time, but there are likely other suitable ways.

var groups = values.Select((s, idx) => (Index: idx / 3, Value: s))
    .GroupBy(x => x.Index);

Where each item in the groups above will be IEnumerable<(Index, Value)>.

You'll also need to be wary of newlines - these may be \r\n in Windows, not just the \n you've indicated.

Here's an example:

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)));
}

Since you've already got commas at the end of each string (including the last one), there's no need to add another separator.

Output:

A2,10.22,-57,
A,10.23,-68,
A2,10.24,-60,
LB,10.25,-62,
StuartLC
  • 104,537
  • 17
  • 209
  • 285
2

Why not use the array that the split gives you instead?

var newArr = a.Split('\n');

for (int i = 0; i < newArr.Length; i += 3)
{
    richTextBox1.Text = newArr[i] + newArr[i + 1] + newArr[i + 2];
}

Just don't forget to check the length of the arrays so that you don't get a IndexOutOfRange Exception.

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
Threezool
  • 453
  • 4
  • 11
1

Try this solution which is a combination of linq and for loop

var result = "";
var items = yourInputString.Split('\n');
for(var i=0; i<items.Count();i=i+3)
{
    result += string.Join(",",items.Skip(i).Take(3))+"\n";
}
Sateesh Pagolu
  • 9,282
  • 2
  • 30
  • 48
1

Try to use Aggregate function

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(); 

Here is the output

enter image description here

Rudresha Parameshappa
  • 3,826
  • 3
  • 25
  • 39
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());

    }
Michael Samteladze
  • 1,310
  • 15
  • 38
1

I'm assuming that the input is actually coming from a file here.

var file = //file path
var sb = new StringBuilder();
var lineNum = 1;
var output = string.Empty;

using (var reader = new StreamReader(file))
{
    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        if (lineNum % 3 == 0)
        {
            output += sb.ToString() + "\n";
            sb.Clear();
        }
        else
            sb.Append(line);

        lineNum++;
    }
}

richTextBox1.Text = output;
Barry O'Kane
  • 1,189
  • 7
  • 12
-1

try this works

    private void button1_Click(object sender, EventArgs e)
{
    //put your string in a textxbox with multiline property set to true
    string[] s = textBox1.Text.Replace("\r", "").Replace("\n", "").Split(',');
    string r = "";
    for (int i = 0; i < s.Length; i++)
    {
        r = r + s[i] + ",";
        if ((i + 1) % 3 == 0)
            r = r + "+";
    }
    if (r.Substring(r.Length - 1, 1) == ",")
        r = r.Substring(0, r.Length - 1);
    if (r.Substring(r.Length - 1, 1) == "+")
        r = r.Substring(0, r.Length - 1);
    string[] finalArrayString = r.Trim().Split('+');

    //just for show the result
    textBox1.Text = "";
    for (int i = 0; i < finalArrayString.Length; i++)
        textBox1.Text = textBox1.Text + finalArrayString[i] + "\r\n";
}

hope it helps you

KillemAll
  • 633
  • 1
  • 10
  • 25