아무래도 문자열은 가지고 노는 정도의 이해도는 있어야 하지 않겠나 싶다.
테스트한 메서드는 제목과 같이 substring, trim, equals, contains, indeoxOf 다.
package training;
public class TestString {
public static void main(String[] args) {
String sample1 = " 2022-02-09 ";
//SubString test, index 번호를 사용함.
System.out.println("1." + sample1.substring(0, 10)); // 인덱스로보면 0~10번째 전 자리까지 출력하네.. 0번 인덱스로부터 1로 카운팅하여 10번째 자리까지 출력.
System.out.println("2." + sample1.substring(1, 10)); // 인덱스로보면 0~10번째 전 자리까지 출력하네.. 비기닝을 1로 바꾼다면?!? 1번 인덱스부터 시작.
System.out.println("3." + sample1.substring(0, sample1.indexOf("-")+1)); //이런식으로도 성이 가능함. 10번째 인덱스부터 출력되었음.
System.out.println("4." + sample1.substring(0, sample1.indexOf("-")+1).trim()); // 공백제거하여 출력.
System.out.println("5." + sample1.substring(0, 10).trim()); //trim() 앞뒤 공백제거
//trim() test
System.out.println("6."+ sample1.trim()); // 공백제거해서 sample1 값 출력함.
//equals test
System.out.println("7." + sample1.trim().equals("02")); //false "02"랑 동일하냐고 물어본거니까.
System.out.println("8."+sample1.equals("02")); //역시 동일함.
//contains test
System.out.println("9."+sample1.trim().contains("02")); //02가 있냐고 물어봤으니 true.
//length test
System.out.println("10."+sample1.length()); //공백포함해서 16
System.out.println("11."+sample1.trim().length()); // 공백제거하니까 10.
//inddxOf는 어떻게 활용하는것인가....
System.out.println("12."+sample1.indexOf("-")); //9번째 인덱스가 '-' 맞음.
System.out.println("13."+sample1.indexOf("2022")); //2022의 2가 시작되는 인덱스번호를 출력.
System.out.println("14."+sample1.indexOf("-", 13)); // fromindex(현재 13)가 더크면 -1을 반환함.
System.out.println("15."+sample1.indexOf("-", 8)); // 그런데 fromindex 상관없이 "-" 의 인덱스번호를 동일하게 출력. 그냥 비교 메서드 정도로 써야하는 메서드인듯.
//여기서 다 잘라버리고 09만 저장해서 출력하고 싶다면 어떡해야할까???
sample1 = sample1.trim().substring(8,10);
System.out.println("16."+sample1);
}
}
결과는 아래와 같다. 어떻게 작용하는지 참고.
1. 2022-
2. 2022-
3. 2022-
4.2022-
5.2022-
6.2022-02-09
7.false
8.false
9.true
10.16
11.10
12.9
13.5
14.-1
15.9
16.09
'개발노트 > Java' 카테고리의 다른 글
로또 번호 생성기 코드 소스 작성 (0) | 2019.12.20 |
---|