String 클래스에서 특정 문자열을 원하는 문자열로 치환하는 방법으로 replace()와 replaceAll(), replaceFirst() 메서드를 쓸 수 있다.
oldChar를 newChar로 변환한 문자열을 반환target 문자열을 replacement 문자열로 변환한 문자열을 반환String replace(char oldChar, char newChar)
String replace(CharSequnce target, CharSequence replacement)
예시
public class StringReplace {
public static void main(String args[]) {
String str = "12345";
System.out.println(str.replace("12", "A")); //A345
}
}
regex와 매치되는 모든 문자열을 replacement 문자열로 변환한 문자열을 반환String replaceAll(String regex, String replacement)
예시
public class StringReplaceAll {
public static void main(String args[]) {
String str = "nice to meet you";
System.out.println(str.replaceAll("[aeiou]", ""); //"nc t mt y"
}
}
regex와 매치되는 첫번째 문자열만 replacement 문자열로 변환한 문자열을 반환String replaceFirst(String regex, String replacement)
예시
public class StringReplaceAll {
public static void main(String args[]) {
String str = "가나다가나다가나다라";
String text = str.replaceFirst("가나다", "마바사");
System.out.println(text); //마바사가나다가나다라
}
}