关于c#:如何将String转换为Int?

How can I convert String to Int?

我有一个TextBoxD1.Text,我想把它转换成int来存储在数据库中。

我该怎么做?


试试这个:

1
int x = Int32.Parse(TextBoxD1.Text);

或者更好的是:

1
2
3
int x = 0;

Int32.TryParse(TextBoxD1.Text, out x);

另外,由于Int32.TryParse返回bool,您可以使用它的返回值来决定解析尝试的结果:

1
2
3
4
5
6
7
int x = 0;

if (Int32.TryParse(TextBoxD1.Text, out x))
{
    // you know that the parsing attempt
    // was successful
}

如果你好奇的话,最好把ParseTryParse的区别总结如下:

The TryParse method is like the Parse
method, except the TryParse method
does not throw an exception if the
conversion fails. It eliminates the
need to use exception handling to test
for a FormatException in the event
that s is invalid and cannot be
successfully parsed. - MSDN


1
Convert.ToInt32( TextBoxD1.Text );

如果您确信文本框的内容是有效的int,请使用此选项。更安全的选项是

1
2
int val = 0;
Int32.TryParse( TextBoxD1.Text, out val );

这将为您提供一些可以使用的默认值。Int32.TryParse还返回一个布尔值,指示它是否能够解析,因此您甚至可以将它用作if语句的条件。

1
2
3
4
5
if( Int32.TryParse( TextBoxD1.Text, out val ){
  DoSomething(..);
} else {
  HandleBadInput(..);
}

1
int.TryParse()

如果文本不是数字,则不会引发。


1
int myInt = int.Parse(TextBoxD1.Text)

另一种方法是:

1
2
3
4
bool isConvertible = false;
int myInt = 0;

isConvertible = int.TryParse(TextBoxD1.Text, out myInt);

两者之间的区别在于,如果文本框中的值无法转换,第一个值将引发异常,而第二个值将返回false。


您需要解析这个字符串,并且还需要确保它是真正的整数格式。

最简单的方法是:

1
2
3
4
5
6
7
8
9
int parsedInt = 0;
if (int.TryParse(TextBoxD1.Text, out parsedInt))
{
   // Code for if the string was valid
}
else
{
   // Code for if the string was invalid
}

1
2
int x = 0;
int.TryParse(TextBoxD1.Text, out x);

Tryparse语句返回一个布尔值,表示分析是否成功。如果成功,解析的值将存储到第二个参数中。

有关详细信息,请参阅int32.triparse方法(string,int32)。


享受它…

1
2
3
4
int i = 0;
string s ="123";
i =int.Parse(s);
i = Convert.ToInt32(s);

对字符使用convert.toint32()时要小心!它将返回字符的UTF-16代码!

如果只在某个位置使用[i]索引运算符访问字符串,它将返回char而不是string

1
2
3
4
5
String input ="123678";

int x = Convert.ToInt32(input[4]);  // returns 55

int x = Convert.ToInt32(input[4].toString());  // returns 7

虽然这里已经有很多描述int.Parse的解决方案,但所有答案中都缺少一些重要的内容。通常,数值的字符串表示形式因区域性而异。数字字符串的元素(如货币符号、组(或千)分隔符和小数分隔符)都因区域性而异。

如果您想创建一种将字符串解析为整数的健壮方法,那么考虑到区域性信息是很重要的。否则,将使用当前区域性设置。这可能会给用户一个相当令人讨厌的惊喜——或者更糟的是,如果您正在分析文件格式。如果您只想进行英语分析,最好通过指定要使用的区域性设置,将其明确化:

1
2
3
4
5
6
var culture = CultureInfo.GetCulture("en-US");
int result = 0;
if (int.TryParse(myString, NumberStyles.Integer, culture, out result))
{
    // use result...
}

有关更多信息,请阅读CultureInfo,特别是msdn上的NumberFormatInfo。


如Tryparse文档中所述,Tryparse()返回一个布尔值,表示找到了一个有效数字:

1
2
3
4
5
6
7
8
9
10
bool success = Int32.TryParse(TextBoxD1.Text, out val);

if (success)
{
// put val in database
}
else
{
// handle the case that the string doesn't contain a valid number
}

你可以写自己的extesion方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static class IntegerExtensions
{
    public static int ParseInt(this string value, int defaultValue = 0)
    {
        int parsedValue;
        if (int.TryParse(value, out parsedValue))
        {
            return parsedValue;
        }

        return defaultValue;
    }

    public static int? ParseNullableInt(this string value)
    {
        if (string.IsNullOrEmpty(value))
        {
            return null;
        }

        return value.ParseInt();
    }
}

在代码中的任何地方都可以调用

1
2
3
int myNumber = someString.ParseInt(); // returns value or 0
int age = someString.ParseInt(18); // with default value 18
int? userId = someString.ParseNullableInt(); // returns value or null

在这种具体情况下

1
int yourValue = TextBoxD1.Text.ParseInt();


你可以使用其中一种,

1
int i = Convert.ToInt32(TextBoxD1.Text);

1
int i =int.Parse(TextBoxD1.Text);

在C中,可以使用以下方法将字符串转换为int:

转换类函数,即Convert.ToInt16()Convert.ToInt32()Convert.ToInt64()或使用ParseTryParse函数。这里给出了一些例子。


stringint的转换可用于:intInt32Int64等反映.NET中整数数据类型的数据类型。

下面的示例显示了此转换:

此显示(for info)数据适配器元素已初始化为int值。这可以直接做到,就像,

1
int xxiiqVal = Int32.Parse(strNabcd);

前任。

1
2
string strNii ="";
UsrDataAdapter.SelectCommand.Parameters["@Nii"].Value = Int32.Parse(strNii );

链接以查看此演示。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//May be quite some time ago but I just want throw in some line for any one who may still need it

int intValue;
string strValue ="2021";

try
{
    intValue = Convert.ToInt32(strValue);
}
catch
{
    //Default Value if conversion fails OR return specified error
    // Example
    intValue = 2000;
}


这就行了

1
2
string x=TextBoxD1.Text;
int xi=Convert.ToInt32(x);

或者你可以使用

1
int xi=Int32.Parse(x);

有关详细信息,请参阅Microsoft Developer Network。


您也可以使用一个扩展方法,这样它将更加可读(尽管每个人都已经习惯了常规的解析函数)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static class StringExtensions
{
    /// <summary>
    /// Converts a string to int.
    /// </summary>
    /// <param name="value">The string to convert.</param>
    /// <returns>The converted integer.</returns>
    public static int ParseToInt32(this string value)
    {
        return int.Parse(value);
    }

    /// <summary>
    /// Checks whether the value is integer.
    /// </summary>
    /// <param name="value">The string to check.</param>
    /// <param name="result">The out int parameter.</param>
    /// <returns>true if the value is an integer; otherwise, false.</returns>
    public static bool TryParseToInt32(this string value, out int result)
    {
        return int.TryParse(value, out result);
    }
}

然后你可以这样称呼它:

  • 如果您确定您的字符串是一个整数,比如"50"。

    1
    int num = TextBoxD1.Text.ParseToInt32();
  • 如果您不确定并想防止崩溃。

    1
    2
    3
    4
    5
    int num;
    if (TextBoxD1.Text.TryParseToInt32(out num))
    {
        //The parse was successful, the num has the parsed value.
    }
  • 为了使其更具动态性,所以您也可以将其解析为double、float等,您可以创建一个通用扩展。


    你可以在没有胰蛋白酶或内置功能的情况下进行如下操作

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    static int convertToInt(string a)
    {
        int x=0;
        for (int i = 0; i < a.Length; i++)
            {
                int temp=a[i] - '0';
                if (temp!=0)
                {
                    x += temp * (int)Math.Pow(10, (a.Length - (i+1)));
                }              
            }
        return x ;
    }


    1
    int x = Int32.TryParse(TextBoxD1.Text, out x)?x:0;


    1
    int i = Convert.ToInt32(TextBoxD1.Text);

    我总是这样做的

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    namespace example_string_to_int
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                string a = textBox1.Text;
                // this turns the text in text box 1 into a string
                int b;
                if (!int.TryParse(a, out b))
                {
                    MessageBox.Show("this is not a number");
                }
                else
                {
                    textBox2.Text = a+" is a number" ;
                }
                // then this if statment says if the string not a number display an error elce now you will have an intager.
            }
        }
    }

    我就是这样做的,希望这能有所帮助。(:


    在parse方法的帮助下,可以将字符串转换为整数值。

    如:

    1
    2
    int val = Int32.parse(stringToBeParsed);
    int x = Int32.parse(1234);

    你可以试试这个,它会起作用的:

    1
    int x = Convert.ToInt32(TextBoxD1.Text);

    变量textbox d1.text中的字符串值将转换为int32并存储在x中。


    方法1

    1
    2
    3
    4
    5
    int  TheAnswer1 = 0;
    bool Success = Int32.TryParse("42", out TheAnswer1);
    if (!Success) {
        Console.WriteLine("String not Convertable to an Integer");
    }

    方法2

    1
    2
    3
    4
    5
    6
    7
    int TheAnswer2 = 0;
    try {
        TheAnswer2 = Int32.Parse("42");
    }
    catch {
        Console.WriteLine("String not Convertable to an Integer");
    }

    方法3

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    int TheAnswer3 = 0;
    try {
        TheAnswer3 = Int32.Parse("42");
    }
    catch (FormatException) {
        Console.WriteLine("String not in the correct format for an Integer");
    }
    catch (ArgumentNullException) {
        Console.WriteLine("String is null");
    }
    catch (OverflowException) {
        Console.WriteLine("String represents a number less than"
                          +"MinValue or greater than MaxValue");
    }


    此代码在Visual Studio 2010中对我有效:

    1
    int someValue = Convert.ToInt32(TextBoxD1.Text);

    如果您要寻找一条很长的路,只需创建一个方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    static int convertToInt(string a)
        {
            int x = 0;

            Char[] charArray = a.ToCharArray();
            int j = charArray.Length;

            for (int i = 0; i < charArray.Length; i++)
            {
                j--;
                int s = (int)Math.Pow(10, j);

                x += ((int)Char.GetNumericValue(charArray[i]) * s);
            }
            return x;
        }

    这对你有帮助;d

    28