[문제]
class Exercise9_3 {
public static void main(String[] args) {
String fullPath = "c:\\jdk1.5\\work\\PathSeparateTest.java";
String path = "";
String fileName = "";
/*
(1) 알맞은 코드를 넣어 완성하시오.
*/
System.out.println("fullPath:"+fullPath);
System.out.println("path:"+path);
System.out.println("fileName:"+fileName);
}
}
[나의 코드]
int index = fullPath.indexOf("work");
path = fullPath.substring(0, index+4);
int nameindex = path.length();
fileName = fullPath.substring(nameindex+1, fullPath.length());
나의 코드는 수동적인 느낌이다. 일일이 짜맞춘 느낌.
[답안]
int pos = fullPath.lastIndexOf("\\");
if(pos!=-1) {
path = fullPath.substring(0, pos);
fileName = fullPath.substring(pos+1);
}
int lastIndexOf (int ch)
지정된 문자 or 문자코드를 문자열의 오른쪽 끝에서부터 찾아서 위치(index)를 알려준다.
못 찾으면 -1을 반환한다. (문자열 오른쪽 끝에서부터 찾으니 pos = 14)를 반환할 것이다.
'프로그래밍 > 코드분석' 카테고리의 다른 글
자바의 정석 연습문제 6-2 (0) | 2016.08.16 |
---|---|
자바의 정석 연습문제 9-4 (0) | 2016.08.13 |
자바의 정석 연습문제 9-1 (0) | 2016.08.13 |
자바의 정석 9-20 코드분석 (0) | 2016.08.12 |
자바의 정석 8-9 코드분석 (0) | 2016.08.09 |