I have string which I split to see if any of the split value is string. If so I want to return true else false.
string words = "1 2 c 5";
Easy approach, I can follow by converting into int array and then compare value side by side.
int[] iar = words.Split(' ').Select(s => int.TryParse(s, out n) ? n : 0).ToArray();
Can any one recommend better approach?
You can simply check without using Split
:
var result = words.Any(c => !char.IsWhiteSpace(c)
&& !char.IsDigit(c));
Or using Split
:
var result = words.Split()
.Any(w => w.Any(c => !char.IsDigit(c)));
The point is you can use char.IsDigit
to check instead of using int.Parse
or int.TryParse
.
You could do this with a simple little method:
public static bool CheckForNum(string[] wordsArr)
{
int i = 0;
foreach (string s in wordsArr)
{
if (Int32.TryParse(s, out i))
{
return true;
}
}
return false;
}
Using:
bool result = CheckForNum(words.Split(' '));
Console.Write(result);
Why not use a regular expression? If a string has words and numbers in it, it must have letters and number characters. I don't entirely understand the logic in your question, so you may need to adjust the logic here.
using System;
using System.Text.RegularExpressions;
...
string words = "1 2 c 5";
Match numberMatch = Regex.Match(words, @"[0-9]", RegexOptions.IgnoreCase);
Match letterMatch = Regex.Match(words, @"[a-zA-Z]", RegexOptions.IgnoreCase);
// Here we check the Match instance.
if (numberMatch.Success && letterMatch.Success)
{
// there are letters and numbers
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.