Programing

C #에서 문자열을 정수로 변환하는 방법

crosscheck 2020. 9. 16. 07:09
반응형

C #에서 문자열을 정수로 변환하는 방법


C #에서 문자열을 정수로 어떻게 변환합니까?


올바르게 구문 분석 할 것이라고 확신하는 경우

int.Parse(string)

그렇지 않은 경우

int i;
bool success = int.TryParse(string, out i);

주의! 아래의 경우 iTryParse.

int i = 10;
bool failure = int.TryParse("asdf", out i);

이는 ref 매개 변수가 아닌 out 매개 변수를 TryParse사용 하기 때문 입니다.


int myInt = System.Convert.ToInt32(myString);

몇 가지 다른 언급 한 것처럼, 당신은 또한 사용할 수 있습니다 int.Parse()int.TryParse().

string이 항상 다음과 같다고 확신하는 경우 int:

int myInt = int.Parse(myString);

string실제로 int첫 번째 인지 확인하려면 :

int myInt;
bool isValid = int.TryParse(myString, out myInt); // the out keyword allows the method to essentially "return" a second value
if (isValid)
{
    int plusOne = myInt + 1;
}

int a = int.Parse(myString);

또는 더 나은 방법은 int.TryParse(string)


string varString = "15";
int i = int.Parse(varString);

또는

int varI;
string varString = "15";
int.TryParse(varString, out varI);

int.TryParse다른 것을 넣으면 varString(예 : "fsfdsfs") 예외가 발생 하므로 더 안전 합니다. int.TryParse문자열을 int로 변환 할 수 없을 때 사용 하면을 반환 0합니다.


문자열에 "실제"숫자가 있다고 확신하거나 발생할 수있는 예외에 익숙하다면 이것을 사용하십시오.

string s="4";
int a=int.Parse(s);

프로세스를 좀 더 제어하려면

string s="maybe 4";
int a;
if (int.TryParse(s, out a)) {
    // it's int;
}
else {
    // it's no int, and there's no exception;
}

다음과 같이하십시오.

var result = Int32.Parse(str);

int i;
string whatever;

//Best since no exception raised
int.TryParse(whatever, out i);

//Better use try catch on this one
i = Convert.ToInt32(whatever);

여기서는 4 가지 기술이 벤치마킹되었습니다.

가장 빠른 방법은 다음과 같습니다.

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

"s"는 int로 변환하려는 문자열입니다. 이 코드는 변환 중에 예외가 없다고 가정합니다. 따라서 문자열 데이터가 항상 일종의 int 값이라는 것을 알고 있다면 위의 코드가 순수한 속도로 이동하는 가장 좋은 방법입니다.

결국 "y"는 int 값을 갖습니다.


bool result = Int32.TryParse(someString, out someNumeric)

This method will try to convert your string someString into int someNumeric, and returning boolean result to you. true if conversion successful and false if conversion failed. Take note that this method will not throw exception if the conversion failed like the Int32.Parse method did and instead it returns zero for someNumeric.

For more information, you can read here:

https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
&
How to convert string to integer in C#


int i;

string result = Something;

i = Convert.ToInt32(result);

You can use either,

    int i = Convert.ToInt32(myString);

or

    int i =int.Parse(myString);

class MyMath
{
    public dynamic Sum(dynamic x, dynamic y)
    {
        return (x+y);
    }
}

class Demo
{
    static void Main(string[] args)
    {
        MyMath d = new MyMath();
        Console.WriteLine(d.Sum(23.2, 32.2));
    }
}

참고URL : https://stackoverflow.com/questions/2344411/how-to-convert-string-to-integer-in-c-sharp

반응형