C# string.split()

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ajc308
    New Member
    • Jul 2007
    • 11

    #1

    C# string.split()

    I have a text file that I am reading in, and on some of the lines, there are multiple numbers that need to be read into seperate variables. The problem I am having, is that sometimes, the numbers are separated by a single space, sometimes multiple spaces, and sometimes tabs.

    So if I have something like the following:
    Code:
    -18519.65	 -100000	-500
    0.0		30.9946	10.0
    -18619.65	-97500	-550
    0.00        30.9846      10.0
    Where the formatting is obviously not consistent, how do I use split effectively to ensure that each line becomes strArray[0], strArray[1], and strArray[2].

    Because currently, what is happening, is that some lines will conform to that standard, but others store the numbers in strArray[0], strArray[2], and strArray[3] or strArray[0], strArray[8], and strArray[14].

    Any thoughts?

    Thanks,
    Andrew
  • TRScheel
    Recognized Expert Contributor
    • Apr 2007
    • 638

    #2
    Something like:

    [code=cpp]
    string fileLocation = "Your File Location"
    StreamReader SReader = new StreamReader(fi leLocation);
    List<string> values = new List<string>();

    while(!SReader. EndOfStream)
    {
    values.AddRange (SReader.ReadLi ne().Split(new char[] { ' ', '\t' }, StringSplitOpti ons.RemoveEmpty Entries);
    }
    [/code]

    That should return only numbers.

    Comment

    Working...