How to convert string to integer in C#

前端 未结 12 1684
我在风中等你
我在风中等你 2020-11-28 08:17

How do I convert a string to an integer in C#?

12条回答
  •  孤街浪徒
    2020-11-28 09:10

    4 techniques are benchmarked here.

    The fastest way turned out to be the following:

    y = 0;
    for (int i = 0; i < s.Length; i++)
           y = y * 10 + (s[i] - '0');
    

    "s" is your string that you want converted to an int. This code assumes you won't have any exceptions during the conversion. So if you know your string data will always be some sort of int value, the above code is the best way to go for pure speed.

    At the end, "y" will have your int value.

提交回复
热议问题