簡體   English   中英

C#-檢查輸入的字符串是否為整數

[英]C# - Check if entered string is a Integer or not

我想檢查輸入的字符串是否為整數,例如

12 =正確

+12 =真

-5 =真

4.4 =錯誤
4as =錯誤

我使用int.TryParse但是我想要的是使用ASCII而不使用int.TryParse

string str;
int strint;
int strintoA;
bool flag = false;

while (flag == false)
{
    Console.Write("Enter a Number : ");
    str = Console.ReadLine();
    flag = int.TryParse(str, out strint);              
    if (flag == false)
    {
        Console.WriteLine("Please Enter Numbers Only.");
    }
    else
    {
        strintoA = strint;
        Console.WriteLine("Entered String: " + str + " is a Number!" );
        break;
    }
}
Console.ReadKey();

您還可以使用正則表達式:

var regex = new Regex(@"^[-+]?\d+$");
var str = Console.ReadLine();
if (regex.IsMatch(str))
{
    Console.WriteLine($"{str} is a number!");
}

為什么不使用:

if(intString[0] == '+' || intString[0] == '-') intString = intString.Substring(1, intString.Length - 1);
bool isNumber = intString.All(char.IsDigit);

檢查第一個字符的-| + |數字,檢查其余的isDigit

for (int i = 0; i < str.Length; i++)
{
    var c = str[i];
    if (i == 0)
    {
        if (!(c == '+' || c == '-' || char.IsDigit(c)) {
            return false;
        }
    }

    if (!char.IsDigit(c)) return false;
}
return true;

不知道為什么不想使用int.TryParse但是下面的代碼應該這樣做:

static bool IsValidInteger(string s)
{
    var leadingSignSeen = false;
    var digitSeen = false;
    var toParse = s.Trim();

    foreach (var c in toParse)
    {
        if (c ==  ' ')
        {
            if (digitSeen)
                return false;
        }
        else if (c == '+' || c == '-')
        {
            if (leadingSignSeen || digitSeen)
                return false;

            leadingSignSeen = true;
        }
        else if (!char.IsDigit(c))
            return false;
        else
        {
            digitSeen = true;
        }
    }

    return true;
}

這將接受帶有前導符號以及前導和尾隨空格的任何整數。 前導符號和數字之間的空格也是可以接受的。

僅供參考:您可以重構代碼以簡化代碼,以獲得完全相同的功能輸出:

void Main()
{
    int result;
    Console.Write("Enter a Number : ");
    while (!int.TryParse(Console.ReadLine(), out result))
    {
        Console.WriteLine("Please Enter Numbers Only.");
        Console.Write("Enter a Number : ");
    }
    Console.WriteLine($"Entered String: {result} is a Number!");
    Console.ReadKey();
}

如果您有充分的理由不使用int.TryParse (例如,它缺少某些功能,或者是要求您編寫自己的練習),則可以使用上述方法將int.TryParse替換為對IsNumericCustom的調用,假定下面的簽名(或將int類型更改為您需要處理的任何數據類型)。

public bool IsNumericCustom(string input, out int output)
{
    //...
}

或者,如果您只關心值是數字而不是解析后的值,則:

void Main()
{
    string result;
    Console.Write("Enter a Number : ");
    //while (!int.TryParse((result = Console.ReadLine()), out _))
    while (!IsNumericCustom((result = Console.ReadLine()))
    {
        Console.WriteLine("Please Enter Numbers Only.");
        Console.Write("Enter a Number : ");
    }
    Console.WriteLine($"Entered String: {result} is a Number!");
    Console.ReadKey();
}

public bool IsNumericCustom(string input)
{
    //...
}

至於IsNumericCustom的邏輯,它實際上取決於您希望實現的目標/為什么int.TryParse / decimal.TryParse等不合適。 這是幾個實現(使用不同的函數名稱)。

using System.Text.RegularExpressions; //https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=netframework-4.7.2
//...
readonly Regex isNumeric = new Regex("^[+-]?\d*\.?\d*$", RegexOptions.Compiled); //treat "." as "0.0", ".9" as "0.9", etc
readonly Regex isInteger = new Regex("^[+-]?\d+$", RegexOptions.Compiled); //requires at least 1 digit; i.e. "" is not "0" 
readonly Regex isIntegerLike = new Regex("^[+-]?\d*\.?\0*$", RegexOptions.Compiled); //same as integer, only 12.0 is treated as 12, whilst 12.1 is invalid; i.e. only an integer if we can remove digits after the decimal point without truncating the value.

//...
public bool IsNumeric(string input)
{
    return isNumeric.IsMatch(input); //if you'd wanted 4.4 to be true, use this
}
public bool IsInteger(string input)
{
    return isInteger.IsMatch(input); //as you want 4.4 to be false, use this
}
public bool IsIntegerLike(string input)
{
    return isIntegerLike.IsMatch(input); //4.4 is false, but both 4 and 4.0 are true 
}

根據您的要求,您似乎想要使用ASCII代碼來斷言輸入的字符串是否為數字。

這是我想出的代碼:

 string str;
    var index = 1;
    int strintoA = 0;
    bool isNegative = false;

    //ASCII list of numbers and signs
    List<int> allowedValues = new List<int> { 43, 45, 48, 49, 50, 51, 52, 53, 54, 55, 56, 
    57 };
    bool flag = false;

    while (!flag)
    {
        Console.WriteLine("Enter a Number : ");

        str = Console.ReadLine();

        if (str.Count(item => allowedValues.Contains((int)item)) == str.Count())
        {
            foreach (var item in str.Reverse())
            {               
                if (item != 43 && item != 45)
                {
                    strintoA += index * (item - 48);
                    index = index * 10;
                }
                else if(item == 45)
                {
                    isNegative = true;
                }
            }
            if(isNegative)
            {
                strintoA *= -1;
            }

            Console.WriteLine("Entered String: " + str + " is a Number!");
            flag = true;
        }
        else
        {
            Console.WriteLine("Please Enter Numbers Only.");
        }
    }
    Console.ReadKey();
}

allowedValues列表包含數字值和允許的符號(+和-)的ASCII表示形式。 foreach循環將重新生成插入的int值。

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM