Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with String parsing

Tags:

c#

I am trying to parse the string and see if the value after ":" is Integer. If it is not integer then remove "Test:M" from string.

Here is the example string I have.

string testString = "Test:34,Test:M";

The result I need testString = "Test:34"

string[] data = testString.Split(',');
for (int i = 0; i < data.Length; i++)
{
    string[] data1 = data[i].Split(':');
    int num = 0;
    if(Int32.TryParse(data1[1], out num))
    {

    }
}
like image 455
nav100 Avatar asked Jul 18 '11 18:07

nav100


3 Answers

You're almost there. Try using this:

    var builder = new StringBuilder();
    string[] data = testString.Split(',');
    for (int i = 0; i < data.Length; i++)
    {
        string[] data1 = data[i].Split(':');
        int num = 0;
        if(Int32.TryParse(data1[1], out num))
        {
            builder.Append(data[i]);
            buidler.Append(',');
        }
    }

    testString = builder.ToString();

EDIT: Adding the "," to keep the comma in the output...

EDIT: Taking @Groo suggestion on avoiding implicit string concatenation.

like image 64
Yuck Avatar answered Nov 10 '22 11:11

Yuck


You could continue on with the looping structure but I, personally, like the look of LINQ a little better:

var dummy = 0;

var intStrings =
    testString.Split(',')
        .Where(s => s.Contains(":") && int.TryParse(s.Split(':')[1], out dummy))
        .ToArray();

var result = String.Join(",", intStrings);
like image 25
Justin Niessner Avatar answered Nov 10 '22 13:11

Justin Niessner


You could just build a new collection with the desired values...

string testString = "Test:34,Test:M, 23:test";

int temp = default( int );

var integerLines =  from line in testString.Split( ',' )
                    let value = line.Split( ':' ).ElementAt( 1 )
                    let isInteger = Int32.TryParse( value, out temp )
                    where isInteger
                    select line;
like image 2
Brandon Moretz Avatar answered Nov 10 '22 12:11

Brandon Moretz