substring() / split() / replace() / replaceAll() / replaceFirst()
substring()
- 원하는 문자열만큼 추출하는 메소드입니다.
- substring(int beginIndex) : 시작 인덱스를 정해주면 시작부터 끝까지의 문자열을 출력합니다
- substring(int beginIndex, endIndex) : 시작 인덱스와 끝 인덱스를 지정해주면 시작부터 끝-1 자리까지 출력합니다.
package com.namji95.javabasic;
public class StringSubstitution {
public static void main(String[] args) {
String s = "가나다라마바사";
// substring()
System.out.println("substring() : " + s.substring(3));
System.out.println("substring() : " + s.substring(3, 6));
}
}
substring() : 라마바사
substring() : 라마바
split()
- 파라미터로 입력한 값을 기준으로 문자열을 나눕니다.
- split(String regex) : 파라미터로 들어온 문자열을 제외하고 문자열을 나눕니다.
- 향상 for문과 일반 for문으로 출력하는 2가지 방법을 사용해 봤습니다.
package com.namji95.javabasic;
public class StringSubstitution {
public static void main(String[] args) {
String s = "가나다라마바사";
String s1 = "가 나 다 라 마 바 사";
// split()
for (String str : s.split("라")) {
System.out.print("split() : " + str + " ");
}
System.out.println();
for (String str1 : s1.split(" ")) {
System.out.print("split() : " + str1 + " ");
}
System.out.println();
String [] str2 = s1.split(" ");
for (int i = 0; i < str2.length; i++) {
System.out.print("split() : " + str2[i] + " ");
}
}
}
split() : 가나다 split() : 마바사
split() : 가 split() : 나 split() : 다 split() : 라 split() : 마 split() : 바 split() : 사
split() : 가 split() : 나 split() : 다 split() : 라 split() : 마 split() : 바 split() : 사
replace()
- 문자열의 특정 문자를 다른 문자로 치환하기 위해 사용합니다.
- replace(CharSequence target, CharSequence replacement) : 모든 target을 replacement로 치환합니다.
package com.namji95.javabasic;
public class StringSubstitution {
public static void main(String[] args) {
String s2 = "가,나,다,라,마,바,사";
// replace()
System.out.println("replace() : " + s2.replace(",", " "));
System.out.println("replace() : " + s2.replace(",", ""));
}
}
replace() : 가 나 다 라 마 바 사
replace() : 가나다라마바사
replaceAll()
- replace()와 비슷하지만, 첫 번째 인자로 정규식을 넣습니다. 즉, 정규식에 맞게 값이 치환됩니다.
- replaceAll(String regex, String replacement) : 첫 번째 인자로 정규식이 들어오고 그 정규식에 맞게 두 번째 인자로 변환됩니다.
- replace()처럼 직접 값을 지정해서 치환하는 것도 가능합니다.
package com.namji95.javabasic;
public class StringSubstitution {
public static void main(String[] args) {
String str = "aaalllbbblllcccllldddllleee";
// replaceAll()
System.out.println("replaceAll() : " + str.replaceAll("[b-c]", "z"));
}
}
replaceAll() : aaalllzzzlllzzzllldddllleee
replaceFirst()
- 첫 번째 발견되는 target만 치환됩니다.
- replaceFirst(String target, String replacement) : 첫 번째 발견되는 target만 replacement로 치환됩니다
package com.namji95.javabasic;
public class StringSubstitution {
public static void main(String[] args) {
String s2 = "가,나,다,라,마,바,사";
// replaceFirst()
System.out.println("replaceFirst() : " + s2.replaceFirst(",", ""));
}
}
replaceFirst() : 가나,다,라,마,바,사