c#语言中怎么样把文本转换成数字,如何将字符串转换为数字 - C# 编程指南 | Microsoft Docs...

如何将字符串转换为数字(C# 编程指南)

02/16/2021

本文内容

你可以调用数值类型(int、long、double 等)中找到的 Parse 或 TryParse 方法或使用 System.Convert 类中的方法将 string 转换为数字。

对预期字符串会包含的数值类型(如 System.Int32 类型)使用 Parse 或 TryParse 方法。 Convert.ToInt32 方法在内部使用 Parse。 Parse 方法返回转换后的数字;TryParse 方法返回布尔值,该值指示转换是否成功,并以 out 参数形式返回转换后的数字。 如果字符串的格式无效,则 Parse 会引发异常,但 TryParse 会返回 false。 调用 Parse 方法时,应始终使用异常处理来捕获分析操作失败时的 FormatException。

调用 Parse 或 TryParse 方法

Parse 和 TryParse 方法会忽略字符串开头和末尾的空格,但所有其他字符都必须是组成合适数值类型(int、long、ulong、float、decimal 等)的字符。 如果组成数字的字符串中有任何空格,都会导致错误。 例如,可以使用 decimal.TryParse 分析“10”、“10.3”或“ 10 ”,但不能使用此方法分析从“10X”、“1 0”(注意嵌入的空格)、“10 .3”(注意嵌入的空格)、“10e1”(float.TryParse 在此处适用)等中分析出 10。 无法成功分析值为 null 或 String.Empty 的字符串。 在尝试通过调用 String.IsNullOrEmpty 方法分析字符串之前,可以检查字符串是否为 Null 或为空。

下面的示例演示了对 Parse 和 TryParse 的成功调用和不成功的调用。

using System;

public static class StringConversion

{

public static void Main()

{

string input = String.Empty;

try

{

int result = Int32.Parse(input);

Console.WriteLine(result);

}

catch (FormatException)

{

Console.WriteLine($"Unable to parse '{input}'");

}

// Output: Unable to parse ''

try

{

int numVal = Int32.Parse("-105");

Console.WriteLine(numVal);

}

catch (FormatException e)

{

Console.WriteLine(e.Message);

}

// Output: -105

if (Int32.TryParse("-105", out int j))

{

Console.WriteLine(j);

}

else

{

Console.WriteLine("String could not be parsed.");

}

// Output: -105

try

{

int m = Int32.Parse("abc");

}

catch (FormatException e)

{

Console.WriteLine(e.Message);

}

// Output: Input string was not in a correct format.

const string inputString = "abc";

if (Int32.TryParse(inputString, out int numValue))

{

Console.WriteLine(numValue);

}

else

{

Console.WriteLine($"Int32.TryParse could not parse '{inputString}' to an int.");

}

// Output: Int32.TryParse could not parse 'abc' to an int.

}

}

下面的示例演示了一种分析字符串的方法,该字符串应包含前导数字字符(包括十六进制字符)和尾随的非数字字符。 在调用 TryParse 方法之前,它从字符串的开头向新字符串分配有效字符。 因为要分析的字符串包含少量字符,所以本示例调用 String.Concat 方法将有效字符分配给新字符串。 对于较大的字符串,可以改用 StringBuilder 类。

using System;

public static class StringConversion

{

public static void Main()

{

var str = " 10FFxxx";

string numericString = string.Empty;

foreach (var c in str)

{

// Check for numeric characters (hex in this case) or leading or trailing spaces.

if ((c >= '0' && c <= '9') || (char.ToUpperInvariant(c) >= 'A' && char.ToUpperInvariant(c) <= 'F') || c == ' ')

{

numericString = string.Concat(numericString, c.ToString());

}

else

{

break;

}

}

if (int.TryParse(numericString, System.Globalization.NumberStyles.HexNumber, null, out int i))

{

Console.WriteLine($"'{str}' --> '{numericString}' --> {i}");

}

// Output: ' 10FFxxx' --> ' 10FF' --> 4351

str = " -10FFXXX";

numericString = "";

foreach (char c in str)

{

// Check for numeric characters (0-9), a negative sign, or leading or trailing spaces.

if ((c >= '0' && c <= '9') || c == ' ' || c == '-')

{

numericString = string.Concat(numericString, c);

}

else

{

break;

}

}

if (int.TryParse(numericString, out int j))

{

Console.WriteLine($"'{str}' --> '{numericString}' --> {j}");

}

// Output: ' -10FFXXX' --> ' -10' --> -10

}

}

调用 Convert 方法

下表列出了 Convert 类中可用于将字符串转换为数字的一些方法。

下面的示例调用 Convert.ToInt32(String) 方法将输入字符串转换为 int。该示例将捕获此方法可能引发的最常见的两个异常:FormatException 和 OverflowException。 如果生成的数字可以在不超过 Int32.MaxValue 的情况下递增,则示例将向结果添加 1 并显示输出。

using System;

public class ConvertStringExample1

{

static void Main(string[] args)

{

int numVal = -1;

bool repeat = true;

while (repeat)

{

Console.Write("Enter a number between −2,147,483,648 and +2,147,483,647 (inclusive): ");

string input = Console.ReadLine();

// ToInt32 can throw FormatException or OverflowException.

try

{

numVal = Convert.ToInt32(input);

if (numVal < Int32.MaxValue)

{

Console.WriteLine("The new value is {0}", ++numVal);

}

else

{

Console.WriteLine("numVal cannot be incremented beyond its current value");

}

}

catch (FormatException)

{

Console.WriteLine("Input string is not a sequence of digits.");

}

catch (OverflowException)

{

Console.WriteLine("The number cannot fit in an Int32.");

}

Console.Write("Go again? Y/N: ");

string go = Console.ReadLine();

if (go.ToUpper() != "Y")

{

repeat = false;

}

}

}

}

// Sample Output:

// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive): 473

// The new value is 474

// Go again? Y/N: y

// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive): 2147483647

// numVal cannot be incremented beyond its current value

// Go again? Y/N: y

// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive): -1000

// The new value is -999

// Go again? Y/N: n

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值