문자열은 불변(immutable)
바로 직전 다룬 문자열편에서 종이에 관한 얘기를 한 적이 있다. 문자열 변수에 다른 값을 넣는다는 것은 기존 종이에 적혀있는 글자를 바꾼다는 것이 아니라, 아예 다른 종이를 만들어서 반환한다는 것이다.
❗️반환형과 인자의 자료형 등을 살펴볼 것
int int1 = "".length(); // int 1: 0
int int2 = "헬로".length(); // int 2: 2
int int3 = "Hello".length(); // int 3: 5
int int4 = "김수한무 거북이와 두루미".length(); // int 4: 13
String str = "Hello World";
int int6 = str.length();
String str1 = "";
String str2 = " \t\n";
int int1 = str1.length(); // int1: 0
int int2 = str2.length(); // int2: 3
// 💡isEmpty : 문자열의 길이가 0인지 여부
boolean bool1 = str1.isEmpty(); // true
boolean bool2 = str2.isEmpty(); // false
// 💡isBlank : 공백(white space)을 제외한 문자열의 길이가 0인지 여부
boolean bool3 = str1.isBlank(); // true
boolean bool4 = str2.isBlank(); // true
이런 메소드들을 다 외우면 좋지만, 굵직한거만 외우고 나머지는 디버깅을 해가면서 알 수 있으니 너무 걱정하지 말자.
String str3 = "\t 에 네 르 기 파!! \n";
// 💡 trim : 앞뒤의 공백(white space) 제거
String str4 = str3.trim();
// str3 : "\t 에 네 르 기 파!! \n"
// str4 : "에 네 르 기 파!!"
String str1 = "아야 슬슬 오함마 준비해야 쓰것다";
// 💡 charAt : ~번째 문자 반환
char ch1 = str1.charAt(0);
char ch2 = str1.charAt(4);
// ⭐️ 마지막 문자 얻기
char ch3 = str1.charAt(str1.length() - 1);
String str2 = "얄리 얄리 얄라셩 얄라리 얄라";
// 💡 indexOf/lastIndexOf : 일치하는 첫/마지막 문자열의 위치
// 앞에서부터 카운트해서 int로 반환
// 두 번째 인자 : ~번째 이후/이전부터 셈
int int1 = str2.indexOf('얄'); // 문자가 정수로 묵시적 변환이 된 것
// int 1:0
int int2 = str2.indexOf('얄', 4); // int2:6
// 인자 이후로 처음 나오는 '얄'의 위치를 반환
int int3 = str2.indexOf("얄라"); // int3:6
int int4 = str2.lastIndexOf("얄라"); // int4:14
// 마지막으로 등장하는 위치를 앞에서부터 센다.
int int5 = str2.lastIndexOf("얄라", 12); // int5:10
// 뒤에 숫자 전에서 마지막으로 등장하는 위치를 앞에서부터 센다.
// 💡 포함되지 않은 문자는 -1 반환
int int6 = str2.indexOf('욜'); // int6:-1
값 동일 여부를 확인하는 것이니까 딱 봐도 boolean값을 반환한다는 것을 알 수 있다.
// 💡 equals : 대소문자 구분하여 비교
String str_a1 = "Hello World"; // 리터럴로 선언
String str_a2 = new String("Hello World"); // 클래스 인스턴스로 선언
String str_a3 = "HELLO WORLD";
boolean bool_a0 = str_a1 == str_a2; // ⚠️ 문자열은 이렇게 비교하지 말 것!
boolean bool_a1 = str_a1.equals(str_a2); // true
boolean bool_a2 = str_a1.equals(str_a3); // false
// 💡 equalsIgnoreCase : 대소문자 구분하지 않고 비교
boolean bool_a3 = str_a1.equalsIgnoreCase(str_a3); // true
boolean bool_a4 = str_a2.equalsIgnoreCase(str_a3); // true
String str_b1 = "옛날에 호랑이가 한 마리 살았어요.";
// 💡 contains : 포함 여부
boolean bool_b1 = str_b1.contains("호랑이"); // true
boolean bool_b2 = str_b1.contains("나무꾼"); // false
// 💡 startsWith : (주어진 위치에서) 해당 문자열로 시작 여부
boolean bool_b3 = str_b1.startsWith("옛날에"); // true
boolean bool_b4 = str_b1.startsWith("호랑이"); // false
boolean bool_b5 = str_b1.startsWith("호랑이", 4); // true
// 💡 startsWith : 해당 문자열로 끝남 여부
boolean bool_b6 = str_b1.endsWith("살았어요."); // true
boolean bool_b7 = str_b1.endsWith("호랑이"); // false
String emailRegex = "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$";
String str_c1 = "yalco@yalco.kr";
String str_c2 = "yalco.yalco.kr";
String str_c3 = "yalco@yalco@kr";
boolean bool_c1 = str_c1.matches(emailRegex); // true
boolean bool_c2 = str_c2.matches(emailRegex); // false
boolean bool_c3 = str_c3.matches(emailRegex); // false
String str_a1 = "ABC";
String str_a2 = "ABCDE";
String str_a3 = "ABCDEFG";
// 💡 compareTo : 사전순 비교에 따라 양수 또는 음수 반환
// 같은 문자열이면 0 반환
int int_a1 = str_a1.compareTo(str_a1); // int_a1:0
// 시작하는 부분이 같을 때는 글자 길이의 차이 반환
int int_a2 = str_a1.compareTo(str_a2); // int_a2:-2
int int_a3 = str_a1.compareTo(str_a3); // int_a3:-4
int int_a4 = str_a2.compareTo(str_a3); // int_a4:-2
int int_a5 = str_a3.compareTo(str_a1); // int_a5:4
String str_a4 = "HIJKLMN";
// 시작하는 부분이 다를 때는 첫 글자의 정수값 차이 반환
int int_a6 = str_a1.compareTo(str_a4); // int_a6:-7
int int_a7 = str_a4.compareTo(str_a3); // int_a7:7
길이가 다를때는 길이의 차이, 문자가 다를때는 문자 정수값의 차이를 반환한다고 보면 된다.
String str_b1 = "abc";
String str_b2 = "DEF";
int int_b1 = str_b1.compareTo(str_b2); // int_b1:29
// 💡 compareToIgnoreCase : 대소문자 구분 없이 비교
int int_b2 = str_b1.compareToIgnoreCase(str_b2); // int_b2:-3
String str_a1 = "Hello, World!";
// 💡 toUpperCase / toLowerCase : 모두 대문자/소문자로 변환
String str_a2 = str_a1.toUpperCase();
String str_a3 = str_a1.toLowerCase();
처음에도 이야기했지만, 이러한 메소드들을 사용한다고 해서 문자열의 원본은 바뀌지 않는다.
String str_b1 = "Hi! How are you? I'm fine. Thank you!";
String str_b2 = "how";
boolean bool_b1 = str_b1.contains(str_b2); // false
// ⭐️ 영문 텍스트에서 대소문자 무관 특정 텍스트 포함 여부 확인시
boolean bool_b2 = str_b1
.toUpperCase()
.contains(str_b2.toUpperCase()); // true
boolean bool_b3 = str_b1
.toLowerCase()
.contains(str_b2.toLowerCase()); // true
지금까지 배운 예제들을 혼자 디버깅하면서 원본은 변하지 않는 것을 확인한다면, 더욱 좋을 것이다.