실무에서 indexOf와 substring을 같이 쓰는 경우가 종종 있다.
예를들어, 파일 이름과 확장자를 분리해서 출력하고 싶은 경우에 사용하면 된다.
public class Test1 {
public static void main(String[] args) {
String file = "hello.txt"; //(확장자를 포함한) 파일명
String ext = ".txt"; //확장자
int extIndex = file.indexOf(ext);
String fileName = file.substring(0, extIndex);
String extName = file.substring(extIndex);
System.out.println("fileName = " + fileName);
System.out.println("extName = " + extName);
}
실행결과
fileName = hello
extName = .txt
- indexOf(String ch) / indexOf(String ch, int fromIndex) : 문자열이 처음 등장하는 위치를 반환.
- lastIndexOf(String ch) : 문자열이 마지막으로 등장하는 위치를 반환.
- substring(int beginIndex) / substring(int beginIndex, int endIndex) : 문자열의 부분 문자열을 반환.
'IT || 개발공부 > Java' 카테고리의 다른 글
[Java] split, join 사용하기 | 자바 단어 분리 | 자바 단어 쪼개기 | 자바 문자 결합 (0) | 2024.04.03 |
---|
댓글