开发者

Help with String parsing

开发者 https://www.devze.com 2023-03-21 07:37 出处:网络
I am trying to parse the string and see if the value after开发者_StackOverflow中文版 \":\" is Integer. If it is not integer then remove \"Test:M\" from string.

I am trying to parse the string and see if the value after开发者_StackOverflow中文版 ":" 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))
    {

    }
}


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.


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);


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;


        string testString = "Test:34,Test:M,Crocoduck:55";
        string[] data = testString.Split(',');
        for (int i = 0; i < data.Length; i++)
        {
            string s = data[i].Remove(0, data[i].IndexOf(':') + 1);
            int num;
            if (Int32.TryParse(s, out num))
            {
                Console.WriteLine(num);
            }
        }


I should warn that don't have coding tool on my hands, so can not provide you with clearly compilable code, but in difference others I would suggest to use Split(string[]), for example: Split(new string[]{",",":"}) and avoid call split 2 times. After this you will get clear view which indexes of the array are integers. In your example it SHOULD be every N*3. You need to test it, by the way.

Hope this helps.

Regards.

0

精彩评论

暂无评论...
验证码 换一张
取 消