.NET/C#
[C#] 문자열 02 - Substring()으로 부분 문자열 가져오기
Dv Jm
2021. 10. 17. 11:34
String.Substring()은 문자열에서 부분 문자열을 가져오는 메서드이다.
1. String.Substring(int startIndex)
문자열의 startIndex 위치부터 문자열의 마지막까지를 새로운 문자열로 생성하여 반환한다.
var result = "This is example string.".Substring(6);
Console.WriteLine(result); // Output : s is example string.
2. String.Substring(int startIndex, int length)
문자열의 startIndex 위치부터 length 만큼의 문자들을 새로운 문자열로 생성하여 반환한다.
var result = "This is example string.".Substring(6, 10);
Console.WriteLine(result); // Output : s is examp
두 메서드 모두 인덱스 범위 초과 오류가 발생할 수 있다.
startIndex는 0 이상, 전체 문자열의 길이 미만이어야 하며, startIndex + length는 0 이상, 전체 문자열의 길이 이하여야 한다.