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))
{
}
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With