如何返回true如果字符串数组有Int和字符串类型的值转换为Int在c#中

本文关键字:字符串 Int 类型 转换 何返回 返回 数组 如果 true | 更新日期: 2023-09-27 18:18:58

我有一个字符串,我分割看看是否有任何分割值是字符串。如果是,我想返回true否则返回false

string words = "1 2 c 5";

简单的方法,我可以将其转换为int数组,然后并排比较值。

int[] iar = words.Split(' ').Select(s => int.TryParse(s, out n) ? n : 0).ToArray();

有谁能推荐更好的方法吗?

如何返回true如果字符串数组有Int和字符串类型的值转换为Int在c#中

您可以简单地检查而不使用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.Parseint.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
}