1

I am using C#. I have scoured the examples, and tried for hours. This situation is different. I can't find a solution.

I have a long string captured from a device on a serial port. The string's format is:

integer,integerCRLFinteger,integerCRLF

(repeats...). Ends with CRLF.

If you show this string in a RichTextBox it looks like:

2442,6266
7727,2727
6320,272
etc... 

So, again, the string's format is

TextWhichIsAnInteger,TextWhichIsAIntegerCRLF

(repeats).

I would like to get it into two arrays (or lists) of type int. And, as a bonus, into a 2 column array or list of paired ints. This is driving me nuts. If you can help provide the code, I will be completely grateful and will worship you forever.

Jeff Atwood
  • 63,320
  • 48
  • 150
  • 153
Ken Barton
  • 21
  • 4

3 Answers3

2

Something like this? From the top of my head. Untested. But it should give you the idea.

using System.Collections.Generic;

List<int> aTypes = new List<int>();
List<int> aValues = new List<int>();

string sInput = "1234,5678\n9876,4321\n";
// Split by linebreak.
string[] aLinebreaks = sInput.Split('\n');
foreach(string sNumericString in aLineBreaks)
{
  // Split by comma.
  string[] aNumbers = sNumericString.Split(',');
  aTypes.Add(Convert.ToInt32(aNumbers[0]);
  aValues.Add(Convert.ToInt32(aNumbers[1]);
}

...

aTypes.ToArray();
aValues.ToArray();
Krumelur
  • 32,180
  • 27
  • 124
  • 263
  • http://stackoverflow.com/questions/3507498/reading-csv-file, http://stackoverflow.com/search?q=%5Bc%23%5D+delimited+lines – sehe Sep 27 '11 at 23:26
  • Thank You Krumelur! You da man. Thank you for the very elegant and very fast response. Sorry for my late response-- I thought stackoverflow was going to send me an email when i got an answer. silly me, anyhow. great solution. cheers! ken... – Ken Barton Oct 01 '11 at 18:33
  • Pleasure. Please accept the answer if it is the one you think that solved your problem. http://meta.stackexchange.com/questions/5234/how-does-accepting-an-apnpswer-work – Krumelur Oct 02 '11 at 08:14
  • Hi Krumelur,I used your approach, it works beautifully and is so versatile for my app. I'm graphing data using the ZedGraph library. Its so cool.In Zedgraph we load a "PointPairList" various ways (it's overloaded) so we can do myPointPairList.add(flt1, flt2), or myPointPairList.add(fltArray1, fltArray2). Anyhow I tried to wrap your code in a function like public void StrToArrays(str, ref Array1, ref Array2). But prior to the call I get error like "cant make unitialized array". Any ideas? How do I declare / initialize the arrays prior to call.Maybe in a class? I dont know their size in advance. – Ken Barton Oct 02 '11 at 10:11
  • That's a new question. But in short: var aYourArray = new string[]; StrToArrays/str, ref aYourArray) { aYourArray = aTypes.ToArray(); } - just onvert the List() of my ode into arrays. And please get a book or tutorial on basi .NET/C# development. – Krumelur Oct 03 '11 at 18:32
1

Why .Replace then .Split ?

Also, Tuples are great tools to make pairs.

    string myNumbers = "123,456,789\r\n";
    myNumbers += "123,456,789\r\n";
    var delimiters = new[] {"\r\n"};
    string[] lines = myNumbers.Split(delimiters, StringSplitOptions.None);
    var result = new List<Tuple<int, int>>();
    foreach (var line in lines)
    {
        var integers = line.Split(',');
        result.Add(Tuple.Create(Int32.Parse(integers[0]), Int32.Parse(integers[1])));
    }
Panos
  • 991
  • 4
  • 5
0

Does something like this work for you?

string input = "2442,6266\r\n7727,2727\r\n1234,1234";

string[] numberGroup = input.Replace("\r\n", ":").Split(':');
IDictionary<int,int> numberPairs = new Dictionary<int, int>();
foreach(string str in numberGroup)
{
    string[] pair = str.Split(',');
    numberPairs.Add(Convert.ToInt32(pair[0]), Convert.ToInt32(pair[1]));
}


foreach(int key in numberPairs.Keys)
{
    Console.WriteLine("Number Pair: [{0}]:[{1}]", key, numberPairs[key]);
}

//Output:
//Number Pair: [2442]:[6266]
//Number Pair: [7727]:[2727]
//Number Pair: [1234]:[1234]

EDIT

If you don't want duplicates there is this way, like Pano pointed out, but I would tell the splitter to remove empty results so it doesn't blow up on one of the index calls in the convert area.

string input = "2442,6266\r\n7727,2727\r\n1234,1234";

string[] numberGroup = input.Split(new[]{"\r\n"}, StringSplitOptions.RemoveEmptyEntries);
IList<Tuple<int, int>> numberPairs = new List<Tuple<int, int>>();
foreach(string str in numberGroup)
{
    string[] pair = str.Split(',');
    numberPairs.Add(Tuple.Create(Convert.ToInt32(pair[0]), Convert.ToInt32(pair[1])));
}


foreach(Tuple<int,int> item in numberPairs)
{
    Console.WriteLine("Number Pair: [{0}]:[{1}]",item.Item1, item.Item2);
}
Cubicle.Jockey
  • 3,288
  • 1
  • 19
  • 31
  • 1
    This won't work if any two pairs share the same first element. For example: `"10,11\r\n12,13\r\n10,14"` – phoog Sep 27 '11 at 23:31
  • wow! cool answer.. thank you for the fast and elegant response... i am about to test it, i never knew to use Dictionary, thats really handy. awesome response, thanks... ken .. – Ken Barton Oct 01 '11 at 18:43
  • Yes, dictionaries are very handy but I often forget that they can't be used if the keys won't be unique. That's why I reminded Cubicle.Jockey :) – phoog Oct 04 '11 at 20:58