2025.07.10 - [코딩테스트] - [PCCP 기출문제] 1번 / 동영상 재생기
위 코딩 테스트 문제를 풀면서 아쉬웠던 문법들에 대해 알아보는 시간을 가지고자 글을 작성하게 되었습니다.
문자열을 숫자로 변환하는 방법 - C#
C#에서 Parse, TryParse 또는 Convert 클래스 메서드를 호출하여 문자열을 숫자로 변환하는 방법을 알아봅니다.
learn.microsoft.com
기본 문법(Int32.Parse 선언부)
public static Int32 Parse(string s, IFormatProvider provider);
public static Int32 Parse(string s, NumberStyles style, IFormatProvider provider);
public static Int32 Parse(string s);
public static Int32 Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null);
public static Int32 Parse(string s, NumberStyles style);
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out Int32 result);
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out Int32 result);
public static bool TryParse(ReadOnlySpan<char> s, out Int32 result);
public static bool TryParse(string s, out Int32 result);
기본적인 string to int Parser의 메서드 선언부는 위와 같습니다. 이때 C#에서 int.Parse or Int32.Parse 로 구분되는데
이는 컴파일 단계에서 Int32.Parse로 모두 변환되어 동일한 방식으로 변환되는 것을 알 수 있습니다.
메서드 선언부의 파라미터에 보이는 다음과 같은 파라미터들에 대해서 알아보겠습니다.
- NumberStyles
- IFormatProvider
- ReadOnlySpan<char>
NumberStyles
IFormatProvider Interface (System)
Provides a mechanism for retrieving an object to control formatting.
learn.microsoft.com
IFormatProvider는 서식 지정을 제어하는 개체를 검색하기 위한 메커니즘을 제공합니다.
public enum NumberStyles
{
None = 0,
AllowLeadingWhite = 1,
AllowTrailingWhite = 2,
AllowLeadingSign = 4,
Integer = 7,
AllowTrailingSign = 8,
AllowParentheses = 16,
AllowDecimalPoint = 32,
AllowThousands = 64,
Number = 111,
AllowExponent = 128,
Float = 167,
AllowCurrencySymbol = 256,
Currency = 383,
Any = 511,
AllowHexSpecifier = 512,
HexNumber = 515
}
AllowLeadingWhite(선행 공백문자 허용)
/// enum value 1
/// 선행 공백문자를 허용함.
/// 허용 범위 (U+0009, U+000A, U+000B, U+000C, U+000D, U+0020)
/// \t, \n, \v, \f, \r, ' '
string num = " 324";
int val = int.Parse(num, NumberStyles.AllowLeadingWhite);
Debug.Log(val);
///Output
///324
AllowTrailingWhite(후행 공백문자 허용)
/// enum value 2
/// 후행 공백문자를 허용함.
/// 허용 범위 (U+0009, U+000A, U+000B, U+000C, U+000D, U+0020)
/// \t, \n, \v, \f, \r, ' '
string num = "324 ";
int val = int.Parse(num, NumberStyles.AllowTrailingWhite);
Debug.Log(val);
///Output
///324
AllowLeadingSign(선행 부호문자 허용)
/// enum value 4
/// 선행 공백문자를 허용함.
/// +(PositiveSign), -(NegativeSign)
string num = "-324";
int val = int.Parse(num, NumberStyles.AllowLeadingSign);
Debug.Log(val);
///Output
///-324
Integer(복합 숫자 스타일)
/// enum value 7
/// AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign 복합 허용
string num = " -324";
int val = int.Parse(num, NumberStyles.Integer);
Debug.Log(val);
///Output
///-324
AllowTrailingSign(후행 부호문자 허용)
/// enum value 8
///NegativeSign(-), PositiveSign(+)
string num = "324-";
int val = int.Parse(num, NumberStyles.AllowTrailingSign);
Debug.Log(val);
///Output
///-324
AllowParentheses(숫자를 둘러싸는 한 쌍의 괄호를 허용)
/// enum value 16
/// 숫자 문자열에 괄호 허용,
string num = "(324)";
int val = int.Parse(num, NumberStyles.AllowParentheses);
Debug.Log(val);
///Output
///-324
AllowDecimalPoint(문자열 내에 DecimalPoint(.)를 허용)
/// enum value 32
/// Decimal Point(.) 허용
string num = "1324.0";
int val = int.Parse(num, NumberStyles.AllowDecimalPoint);
Debug.Log(val);
///Output
///1324
AllowThousands(문자열 내에 천의 자리 구분자 콤마(,) 허용)
/// enum value 64
/// 천의 자리 구분자, 허용
string num = "1,123,324";
int val = int.Parse(num, NumberStyles.AllowThousands);
Debug.Log(val);
///Output
///1123324
Number(복합 숫자 스타일)
/// enum value 111
/// 1 + 2 + 4 + 8 + 32 + 64
/// 앞의 각 enum들의 허용 문자들을 포함하여 허용하는 경우.
/// 후행 부호, 선행 부호, 선행 공백, 후행 공백, DecimalPoint, 천의 자리 구분자
string num = " -1,123,324";
int val = int.Parse(num, NumberStyles.Number);
Debug.Log(val);
///Output
///1123324
AllowExponent (exponent [지수] 허용)
/// enum value 128
/// exponent(지수) 허용
string num = "2e+4";
int val = int.Parse(num, NumberStyles.AllowExponent);
Debug.Log(val);
///Output
///20000
Float
/// enum value 167
/// 1 + 2 + 4 + 32 + 128 실수 타입의 복합 문자열 스타일
/// 선행 공백, 후행 공백, 선행 부호, 소수점 허용, 지수 문자 허용
string num = " +2e+4";
int val = int.Parse(num, NumberStyles.AllowExponent );
Debug.Log(val);
///Output
///20000
AllowCurrencySymbol
/// enum value 256
/// 숫자 문자열에 통화 기호가 포함될 수있음. CurrencySymbol 속성으로 결정
string num = "1234₩";
int val = int.Parse(num, NumberStyles.AllowCurrencySymbol );
Debug.Log(val);
///Output
///1234
Currency
/// enum value 383
/// AllowExponent 및 AllowHexSpecifier를 제외한 복합 숫자 스타일
/// 0b0101111111
string num = " 1,234₩";
int val = int.Parse(num, NumberStyles.Currency);
Debug.Log(val);
///Output
///1234
Any
/// enum value 511
/// AllowExponent 및 AllowHexSpecifier 를 제외한 스타일 허용 복합 숫자 스타일
/// 0b0111111111
string num = " 1,234+₩";
int val = int.Parse(num, NumberStyles.Any);
Debug.Log(val);
///Output
///1234
AllowHexSpecifier
/// enum value 512
/// 문자열이 16진수 문자열을 포함할 수있음.
string num = "ABCD";
int val = int.Parse(num, NumberStyles.AllowHexSpecifier);
Debug.Log(val);
///Output
///43981
HexNumber (복합 숫자 스타일)
/// enum value 515
/// 512 + 1 + 2
/// 문자열에 16진수 문자를 포함할 수있고, 선행 공백, 후행 공백 허용 복합 숫자 문자열
string num = "ABCD ";
int val = int.Parse(num, NumberStyles.HexNumber);
Debug.Log(val);
///Output
///43981
NumberStyles을 정리하며..
NumberStyles를 정리해 보니 다양한 문자열을 변환할 수 있는 것을 알게 되었고, enum의 특성을 활용하여, 복합 숫자 스타일을 활용할 수있다는 것을 알게되었다. enum을 파라미터로 활용하는 경우에는 비트 or 연산(|)을 통해 다양한 복합 숫자 스타일을 만들어 적용할 수 있다는 것을 알게되었고, 이번 기회에 예제를 통해 하나씩 결과를 출력해 보니, 더 기억에 남을 수 있었습니다.
NumberStyles의 분량이 많아져 IFormatProvider, ReadOnlySpan <char>에 대한 내용은 다음 글을 통해 정리해보려고 합니다.