public class StringEx1 {
public static void main(String[] args) {
//replace()
String str1 = "Hello World";
String reStr1 = str1.replace("l", "L");
System.out.println("str1 :" + str1);
System.out.println("reStr1 :" + reStr1);
//replaceAll()
String str2 = "Hello World";
String reStr2 = str2.replace("l", "L");
System.out.println("str2 :" + str2);
System.out.println("reStr2 :" + reStr2);
}
}
str1 : Hello World
reStr1 : HeLLo WorLd
str2 : Hello World
reStr2 : HeLLo WorLd
replace()와 replaceAll() 두 메소드 모두 특정 문자열을 새로운 문자열로 대체된 결과(String)을 반환한다.
| Method | 설명 |
|---|---|
| String replace(CharSequence old, CharSequence new) | 특정 문자열 중 old 문자열을 새로운 new 문자열로 모두 바꾼 문자열을 반환한다. |
| String replaceAll(String regex, String replacement) | 특정 문자열 중 지정된 문자열 regex와 일치하는 모든 문자를 새로운 문자열 replacemet로 변경한다. |
replace()는 특정 문자열을 새로운 문자열로 대체하기 위한 메소드
replaceAll()은 특정한 정규식에 일치하는 문자열을 전부 다른 문자열로 대체하기 위한 메소드이다.
public class StringEx1 {
public static void main(String[] args) {
//replace()
String str1 = "helloworld에 오신 것을 welcome합니다~";
String reStr1 = str1.replace("helloworld에", "").replace("welcome", "");
System.out.println("str1 :" + str1);
System.out.println("reStr1 :" + reStr1);
//replaceAll()
String str2 = "helloworld에 오신 것을 환영합니다~";
String reStr2 = str2.replace("[a-z]", "");
System.out.println("str2 :" + str2);
System.out.println("reStr2 :" + reStr2);
}
}
str1 : helloworld에 오신 것을 welcome합니다~
reStr1 : 에 오신 것을 합니다~
str2 : helloworld에 오신 것을 welcome합니다~
reStr2 : 에 오신 것을 합니다~
replace()는 특정 문자열을 대체할 때
replaceAll()은 특정 패턴의 문자열을 대체할 때(영소문자 전체, 숫자 전체 등) 사용한다.