C#:實現一個將字符串轉換為整數的方法


具體代碼如下:暫不支持浮點數四舍五入操作

 1        static void Main(string[] args)
 2         {
 3             string numStr = "-177.00";
 4             int num;
 5             string isSuccess=IntParse(numStr, out num)?"Yes":"No";
 6             Console.WriteLine($"字符串:{numStr} \n是否轉換成功:{isSuccess}\n轉換為整數:{num}");
 7             Console.ReadKey();                          
 8         }
 9         private static bool IntParse(string str,out int res)
10         {
11             Dictionary<string, int> numDic = new Dictionary<string, int>
12             {
13                 {"0",0 },
14                 {"1",1 },
15                 {"2",2 },
16                 {"3",3 },
17                 {"4",4 },
18                 {"5",5 },
19                 {"6",6 },
20                 {"7",7 },
21                 {"8",8 },
22                 {"9",9 }
23             };
24             bool isNegative = false;
25             res = 0;
26             if (!String.IsNullOrEmpty(str))
27             {
28                 //符號位
29                 if (str.Contains("-"))
30                 {
31                     isNegative = true;
32                     str = str.Replace("-", "");
33                 }
34                 //小數位
35                 if (str.Contains("."))
36                 {
37                     //暫時先不進行四舍五入
38                     str = str.Substring(0, str.IndexOf("."));
39                 }
40                 char[] nums = str.ToArray();
41                 try
42                 {
43                     for (int i = 0; i < nums.Length; i++)
44                     {
45 
46                         int n = numDic[nums[i].ToString()];
47                         if (res != 0)
48                             res = res * 10 + n;
49                         else
50                             res = n;
51                     }
52                 }
53                 catch
54                 {
55                     return false;
56                 }
57                 if (isNegative)
58                     res=-res;
59                 return true;             
60             }
61             return false;
62         }

運行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM