Function:
<summary>//ToInt//</summary>/<param name= "str" ></param> <returns></returns> public static int atoi (String str) {string strnew = str. Trim (); string ch = strnew.substring (0, 1); string result = ""; int bl = 0; Double re; BOOL flag = TRUE; for (int i = 1; i < strnew.length; i++) {string s = strnew.substring (i, 1); if (int. TryParse (s, out BL)) {if (Convert.ToInt32 (s) = = 0) continue; Switch (CH) {case "0": result = Res Ult + s.tostring (); Break Case "+": result = result + s.tostring (); Break Case "-": Flag = false; result = result + s.tostring (); Break Default:if (i = = 1) result = result + ch. ToString (); result = result + s.tostring (); Break }} else break; } if (!string. IsNullOrEmpty (Result)) {re = convert.todouble (result); if (!flag) re =-re; if (re < int. MinValue | | Re > int. MaxValue) re = 0; } else re = 0; return (int) re; }
Console display:
static void Main (string[] args) { Console.WriteLine ("Please enter a string to convert:"); String str = Console.ReadLine (); int re = atoi (str); if (Re! = 0) Console.WriteLine ("After conversion:" + re); Else Console.WriteLine ("The string cannot be converted to an integer!") "); Console.readkey (); }
Leetcode Series---atoifunction c#code