[英]How to Return true if String array having mix of Int and String type value converted to int in C#
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.
如果是这样,我想返回true,否则返回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数组,然后并排比较值。
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
: 您可以简单地检查而不使用
Split
:
var result = words.Any(c => !char.IsWhiteSpace(c)
&& !char.IsDigit(c));
Or using Split
: 或使用
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
. 关键是您可以使用
char.IsDigit
进行检查,而不是使用int.Parse
或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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.