💚 문자열을 자르는 substring
- 문자열을 원하는 구간만큼 잘라야 하는 경우가 있다. 이때 사용하는 것이 String 클래스의 substring 메서드이다.
- substring은 두 종류가 있다.
① substring(int beginIndex)
beginIndex부터(포함해서) 문자열의 끝까지 자른다.
② substring(int beginIndex, int endIndex)
beginIndex부터(포함해서) endIndex 전까지 자른다.
ex) endIndex가 5라면 index 4까지만 자른다.
💚 substring 예시
public class substringTest {
public static void main(String[] args) {
String str1 = "Hello, World!";
String str2 = str1.substring(7);
String str3 = str1.substring(0, 5);
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
}
}
- 출력 결과
Hello, World!
World!
Hello
Hello와 World 사이의 ','가 5번 인덱스, 공백이 6번 인덱스임을 참고.
공식 docs
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
String (Java Platform SE 8 )
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argum
docs.oracle.com
'Programming > Java' 카테고리의 다른 글
[Java] Map 인터페이스의 value 변경하는 법 (0) | 2023.06.12 |
---|---|
[Java] Comparator 인터페이스의 compare 메서드 (0) | 2023.05.30 |
[Java] ArrayList 오름차순/내림차순 정렬 방법 (0) | 2023.03.30 |
[Java] key-value 쌍을 가지는 Map 자료구조 인터페이스 (0) | 2023.03.24 |
[Java] 다중 for문 탈출하기 (0) | 2023.02.18 |
댓글