숫자가 있는 문자열은 int.TryParse를 사용하여 검증할 수 있습니다. 또는 int.Parse .
Int.Parse는 문자열을 정수로 구문 분석할 수 없는 경우 예외를 throw하는 반면 Int.TryParse는 성공 여부를 나타내는 bool을 반환합니다. 또한 Int.TryParse에는 구문 분석된 문자열의 값을 갖는 out 매개변수가 있습니다.
예
using System;
namespace DemoApplication {
class Program {
static void Main(string[] args) {
string numberString = "123";
int number = 0;
if(int.TryParse(numberString, out number)) {
Console.WriteLine($"Try Parse Interger Number: {number}");
}
Console.WriteLine($"Parse Interger Number: {int.Parse(numberString)}");
Console.ReadLine();
}
}
} 출력
코드의 출력은
Try Parse Interger Number: 123 Parse Interger Number: 123
위의 예에서 int.Tryparse는 out 매개변수의 구문 분석된 문자열과 함께 부울 값을 반환하므로 if 조건은 true를 반환합니다. 또한 int.Parse는 문자열에 적절한 숫자가 포함되어 있으므로 정수 값을 반환합니다.
예
using System;
namespace DemoApplication {
class Program {
static void Main(string[] args) {
string numberString = "A123";
int number = 0;
if(int.TryParse(numberString, out number)) {
Console.WriteLine($"Try Parse Interger Number: {number}");
}
elsem{
Console.WriteLine($"String doesnot have a proper number");
}
Console.ReadLine();
}
}
} 출력
위 코드의 출력은
String doesnot have a proper number
문자열에 적절한 숫자가 없기 때문에 int.Tryparse는 false를 반환하고 코드의 else 부분이 실행됩니다. 같은 경우 int.Parse는 아래와 같이 예외를 던집니다.
예
using System;
namespace DemoApplication {
class Program {
static void Main(string[] args) {
string numberString = "A123";
Console.WriteLine($"Parse Interger Number: {int.Parse(numberString)}");
//Exception: Input string was not in correct format.
}
}
}