Help with parsing strings

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

Here is an example that I have.

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

As a 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)) { } } 
+6
source share
5 answers

You can continue to work with the loop structure, but I personally, like the appearance of LINQ, are 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); 
+4
source

You are 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 a "," to save a comma in the output ...

EDIT : Accept @Groo's suggestion to avoid implicit string concatenation.

+5
source

You can simply create 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; 
+2
source
  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); } } 
+1
source

I have to warn that I don’t have any tools for coding on hand, so I can’t provide you with explicitly compiled code, but unlike others, I would suggest using Split (string []), for example: Split (new line [] {", ",": "}}) and avoid breaking the call 2 times. After that, you get a clear idea of ​​which array indices are integers. Each N * 3 MUST be in your example. By the way, you need to test it.

Hope this helps.

Sincerely.

0
source

Source: https://habr.com/ru/post/893009/


All Articles