[英]How to Return true if String array having mix of Int and String type value converted to int in C#
我有分割的字符串,看是否有任何分割值是字符串。 如果是这样,我想返回true,否则返回false。
string words = "1 2 c 5";
简单的方法,我可以将其转换为int数组,然后并排比较值。
int[] iar = words.Split(' ').Select(s => int.TryParse(s, out n) ? n : 0).ToArray();
有人可以推荐更好的方法吗?
您可以简单地检查而不使用Split
:
var result = words.Any(c => !char.IsWhiteSpace(c)
&& !char.IsDigit(c));
或使用Split
:
var result = words.Split()
.Any(w => w.Any(c => !char.IsDigit(c)));
关键是您可以使用char.IsDigit
进行检查,而不是使用int.Parse
或int.TryParse
。
您可以使用一个简单的小方法来做到这一点:
public static bool CheckForNum(string[] wordsArr)
{
int i = 0;
foreach (string s in wordsArr)
{
if (Int32.TryParse(s, out i))
{
return true;
}
}
return false;
}
使用方法:
bool result = CheckForNum(words.Split(' '));
Console.Write(result);
为什么不使用正则表达式? 如果字符串中包含单词和数字,则必须包含字母和数字字符。 我对您问题的逻辑不完全理解,因此您可能需要在此处调整逻辑。
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.