Richeek Dey
Richeek Dey

Reputation: 257

Split Array into 2D based on 2 parameters C#

I have a text file which I have split up into a string array based on new line.

string[] arr = s.Split('\n');

Now, I need to further categorize this into a 2-dimensional array wherein each column is a new "transaction". So the text file basically contains info about bank transactions, an example being given below:

21...... 22.... 23..... 31.... 32..... 31..... 32..... 21.... 21..... 22....

The beginning of the numbers signify a new tx record which begins at a new line. I want to make it into a 2D array wherein each column is grouped as one tx beginning from 21 until it comes across the next 21 (so the record before it).

 for (int i = 0; i < arr.Length; i++)
        {
            if (arr[i].StartsWith("21")) 
            {
                indices[i] = i;
            }
        }

I tried to write the code above to check for array element beginning with 21 and then storing the index but it ends up storing all the indices.

Any help will be appreciated!

Upvotes: 2

Views: 244

Answers (2)

Jakub Dąbek
Jakub Dąbek

Reputation: 1044

What you'd need to do is

string[] arr = s.Split('\n');

List<List<string>> listOfLists = new List<List<string>>(); //dynamic multi-dimensional list

//list to hold the lines after the line with "21" and that line
List<string> newList = new List<string>();  
listOfLists.Add(newList);

for(int i = 0; i < arr.Length; i++)
{
    if(arr[i].StartsWith("21"))
    {
        if(newList.Count > 0)
        {                
            newList = new List<string>();  //make a new list for a column
            listOfLists.Add(newList);      //add the list of lines (one column) to the main list
        }
    }
    newList.Add(arr[i]);  //add the line to a column
} 

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

If I understand you right, you can try regular expressions (i.e. instead of splitting, extract transactions):

  using System.Linq;
  using System.Text.RegularExpressions;

  ... 

  string line = "21 A 22 B 23 C 31 D 32 E 31 F 32 G 21 H 21 I 22 J";

  var result = Regex
    .Matches(line, "21 .*?((?=21 )|$)")
    .OfType<Match>()
    .Select(match => match.Value)
    .ToArray(); // <- let's materialize as na array

  Console.Write(string.Join(Environment.NewLine, result));

Outcome:

21 A 22 B 23 C 31 D 32 E 31 F 32 G 
21 H 
21 I 22 J

Upvotes: 1

Related Questions