Hey...i am doing Split now.
But, my split method cannot function well. I want split my text file content from horizontal to vertical. But, my output always got problem.

for example

my text file content is like this..
eg.
1 2 3 4 5
2 3 4 5

my output wants like this
1 2
2 3
3 4
4 5
5
but my output always give me like this
1
2
3
4
5
2
3
4
5

So, how to solve it? And how to show it in the textbox??

StringBuilder sb = new StringBuilder();
                    string line;
                    string Temp = " ";

                    if (File.Exists(fileOpen.FileName)) 
                    {

                        StreamReader file = null;
                        try 
                        {
                            file = new StreamReader(fileOpen.FileName);
                            while ((line = file.ReadLine()) != null)
                            {
                                sb.AppendLine(line);
                            }
                           // textBox1.Text = sb.ToString();
                           
                            
                                
                            foreach (string lines in File.ReadAllLines(fileOpen.FileName))
                            {
                                 string[] Split = lines.Split(new string[] { " ", "\n", "\r", "\t" }, StringSplitOptions.RemoveEmptyEntries);

                                foreach (string Splits in Split)
                                {
                                    Temp = Temp + "\n" + Split;
                                }

                                //show line by line after split
                                MessageBox.Show(Temp, "read by line");
                            }
                          
                            


                        }

this is the coding..hope someone can help me?

Dani AI

Generated

The problem is a transpose of whitespace-separated tokens: each column across the input lines should become a new row. The original snippet from has three practical bugs that produce the wrong output: appending the whole array instead of the current token (so the wrong variable is concatenated), showing the result inside the inner loop (causes repeated MessageBox dialogs), and starting with a leading space which yields an extra blank line. ’s “use .Split(' ')” works only for simple single-space input; prefer a split on any whitespace to be robust. ’s dictionary idea and ’s two-line approach are both valid patterns depending on whether the file has a fixed number of lines or an arbitrary number.

A clear, safe approach:

  • Read all lines, split each line on any whitespace into token arrays.
  • Find the longest token count (max columns).
  • For each column index, collect the token from each row (if present) and join them with a tab or space.
  • Build a single StringBuilder result and set it once to the multiline TextBox.

Example implementation (keeps tokens in order, handles ragged rows):

using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;

// Transpose file tokens into a multiline TextBox
void TransposeFileToTextBox(string path, System.Windows.Forms.TextBox box)
{
    var rows = File.ReadAllLines(path)
                   .Select(line => Regex.Split(line.Trim(), @"\s+"))
                   .ToArray();

    int maxCols = rows.Length == 0 ? 0 : rows.Max(r => r.Length);
    var sb = new StringBuilder();

    for (int col = 0; col < maxCols; col++)
    {
        var items = new List<string>();
        for (int row = 0; row < rows.Length; row++)
            if (col < rows[row].Length)
                items.Add(rows[row][col]);

        while (items.Count > 0 && string.IsNullOrEmpty(items[items.Count - 1]))
            items.RemoveAt(items.Count - 1);

        if (items.Count > 0)
            sb.AppendLine(string.Join("\t", items));
    }

    box.Multiline = true;
    box.Text = sb.ToString();
}

Troubleshooting notes: move any MessageBox.Show calls outside loops, avoid initializing the accumulator with leading whitespace, and set the TextBox to a monospace font or use PadRight for aligned columns if visual alignment is needed. For very large files, build column lists incrementally instead of storing the whole file in memory.

Recommended Answers

All 4 Replies

:)
Check this out man:

private void method()
        {
            string allText = "1, 2, 3, 4, 5\n2, 3, 4, 5";
            allText = allText.Replace(",", "");
            string[] lines = allText.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);

            Dictionary<int, List<int>> dic = new Dictionary<int, List<int>>();

            for (int i = 0; i < lines.Length; i++)
            {
                string[] _Chars = lines[i].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

                int counter = 0;
                foreach (string _char in _Chars)
                {
                    int number = Convert.ToInt32(_char);
                    if (dic.ContainsKey(counter))
                        dic[counter].Add(number);
                    else
                    {
                        List<int> list = new List<int>();
                        list.Add(number);
                        dic.Add(counter, list);
                    }
                    counter++;
                }
            }

            //NOW lets show what we got:
            string rows = null;
            foreach (KeyValuePair<int, List<int>> item in dic)
            {
                for (int i = 0; i < item.Value.Count; i++)
                    rows += item.Value[i] + " ";
                rows = rows + Environment.NewLine;
            }
            MessageBox.Show("List of new items:\n\n" + rows);
        }

What can you say? Just tell me if you understand the code?!
I have decided to use a Dictonary with adding keys and values into it.
Mitja

just use .split(' '); into an array

using System;
using System.IO;

namespace TestBed {
    class Program {
        static void Main(string[] args) {
            String[] lines = File.ReadAllLines("data.txt");
            String[] first = lines[0].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            String[] second = lines[1].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            for (int i = 0; i < first.Length; i++) {
                Console.WriteLine("{0} {1}", first[i], i >= second.Length ? " " : second[i]);
            }

            Console.ReadLine();
        }
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.