码迷,mamicode.com
首页 > 其他好文 > 详细

字符格式转换

时间:2018-01-20 22:50:05      阅读:328      评论:0      收藏:0      [点我收藏+]

标签:from   long   move   clu   show   letter   null   oid   parse   

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

Visual Studio 2015

其他版本

 

 

若要了解有关 Visual Studio 2017 RC 的最新文档,请参阅 Visual Studio 2017 RC 文档

可以使用 Convert 类中的方法或使用各种数值类型(int、long、float 等)中的 TryParse 方法将字符串转换为数字。

如果你具有字符串,则调用 TryParse 方法(例如 int.TryParse(“11”))会稍微更加高效且简单。 使用 Convert 方法对于实现 IConvertible 的常规对象更有用。

可以对预期字符串会包含的数值类型(如 System.Int32 类型)使用 Parse 或 TryParse 方法。 Convert.ToUInt32 方法在内部使用 Parse。 如果字符串的格式无效,则 Parse 会引发异常,而 TryParse 会返回 false

示例

 

Parse 和 TryParse 方法会忽略字符串开头和末尾的空格,但所有其他字符必须是组成合适数值类型(int、long、ulong、float、decimal 等)的字符。 组成数字的字符中的任何空格都会导致错误。 例如,可以使用 decimal.TryParse 分析“10”、“10.3”、“ 10 ”,但不能使用此方法分析从“10X”、“1 0”(注意空格)、“10 .3”(注意空格)、“10e1”(float.TryParse 在此处适用)等中分析出 10。

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

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
            int numVal = Int32.Parse("-105");
            Console.WriteLine(numVal);
            // Output: -105
            // TryParse returns true if the conversion succeeded
            // and stores the result in j.
            int j;
            if (Int32.TryParse("-105", out 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.
            string inputString = "abc";
            int numValue;
            bool parsed = Int32.TryParse(inputString, out numValue);
if (!parsed)
                Console.WriteLine("Int32.TryParse could not parse ‘{0}‘ to an int.\n", inputString);
// Output: Int32.TryParse could not parse ‘abc‘ to an int.
            // This snippet shows a couple of examples that extract number characters from the
            // beginning of the string to avoid TryParse errors.
            StringBuilder sb = new StringBuilder();
            var str = "  10FFxxx";
            foreach (char c in str) {
                // Check for numeric characters (hex in this case).  Add "." and "e" if float,
                // and remove letters.  Include initial space because it is harmless.
                if ((c >= 0 && c <= 9) || (c >= A && c <= F) || (c >= a && c <= f) || c ==  ) {
                    sb.Append(c);
                }
                else
                    break;
            }
            if (int.TryParse(sb.ToString(), System.Globalization.NumberStyles.HexNumber, null, out i))
                Console.WriteLine(sb.ToString());
str = "   -10FFXXX";
            sb.Clear();
            foreach (char c in str) {
                // Check for numeric characters (allow negative in this case but no hex digits). 
                // Though we use int.TryParse in the previous example and this one, int.TryParse does NOT
                // allow a sign character (-) AND hex digits at the same time.
                // Include initial space because it is harmless.
                if ((c >= 0 && c <= 9) || c ==   || c == -) {
                    sb.Append(c);
                } else
                    break;
            }
            if (int.TryParse(sb.ToString(), out i))
                Console.WriteLine(sb.ToString());

 

示例

 

下表列出了 Convert 类中可使用的一些方法。

数值类型

方法

decimal

ToDecimal(String)

float

ToSingle(String)

double

ToDouble(String)

short

ToInt16(String)

int

ToInt32(String)

long

ToInt64(String)

ushort

ToUInt16(String)

uint

ToUInt32(String)

ulong

ToUInt64(String)

此示例调用 Convert.ToInt32(String) 方法将输入的 string 转换为 int。 代码将捕获此方法可能引发的最常见的两个异常:FormatExceptionOverflowException。 如果该数字可以递增而不溢出整数存储位置,则程序使结果加上 1 并打印输出。

 1 using System;
 2 using System.Linq;
 3 using System.Collections;
 4 using System.Collections.Generic;
 5         static void Main(string[] args)
 6         {
 7             int numVal = -1;
 8             bool repeat = true;
 9 while (repeat)
10             {
11                 Console.WriteLine("Enter a number between ?2,147,483,648 and +2,147,483,647 (inclusive).");
12 string input = Console.ReadLine();
13 // ToInt32 can throw FormatException or OverflowException.
14                 try
15                 {
16                     numVal = Convert.ToInt32(input);
17                 }
18                 catch (FormatException e)
19                 {
20                     Console.WriteLine("Input string is not a sequence of digits.");
21                 }
22                 catch (OverflowException e)
23                 {
24                     Console.WriteLine("The number cannot fit in an Int32.");
25                 }
26                 finally
27                 {
28                     if (numVal < Int32.MaxValue)
29                     {
30                         Console.WriteLine("The new value is {0}", numVal + 1);
31                     }
32                     else
33                     {
34                         Console.WriteLine("numVal cannot be incremented beyond its current value");
35                     }
36                 }
37                 Console.WriteLine("Go again? Y/N");
38                 string go = Console.ReadLine();
39                 if (go == "Y" || go == "y")
40                 {
41                     repeat = true;
42                 }
43                 else
44                 {
45                     repeat = false;
46                 }
47             }
48             // Keep the console open in debug mode.
49             Console.WriteLine("Press any key to exit.");
50             Console.ReadKey();    
51         }
52         // Sample Output:
53         // Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
54         // 473
55         // The new value is 474
56         // Go again? Y/N
57         // y
58         // Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
59         // 2147483647
60         // numVal cannot be incremented beyond its current value
61         // Go again? Y/N
62         // Y
63         // Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
64         // -1000
65         // The new value is -999
66         // Go again? Y/N
67         // n
68         // Press any key to exit.

 

 

来自 <https://msdn.microsoft.com/zh-cn/library/bb397679.aspx>

 

字符格式转换

标签:from   long   move   clu   show   letter   null   oid   parse   

原文地址:https://www.cnblogs.com/pugongying123/p/8322052.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!