프로그래밍/JAVA Spring

[JAVA 자바] contains()를 이용한 문자열 포함 여부 확인/replace()를 이용한 문자열 치환

hectick 2022. 1. 23. 01:05

문자열 포함 여부 확인

contains()

문자열이 특정 문자열을 포함하고 있는지 확인한다.

포함하고 있으면 true를, 아니면 false를 반환하며, 대소문자를 구분한다.

import java.io.*;

public class Main {
	public static void main(String[] args) {
		String str = "Hello my name is hectick, not hectic";
		
		System.out.println(str.contains("hello")); //false 출력
		System.out.println(str.contains("Hello")); //true 출력
		System.out.println(str.contains("hectick")); //true 출력
	}
}

 

문자열 치환

replace()

문자열의 모든 oldChar를 newChar로 바꾼다

replace(char oldChar, char newChar)

특정 문자열(target)과 일치하는 하위 문자열을 원하는 문자열(replacement)로 바꾼다.

replace(CharSequence target, CharSequence replacement)
import java.io.*;

public class Main {
	public static void main(String[] args) {
		String str = "Hello my name is hectick, not hectic";

		str = str.replace('o', '5');
		System.out.println(str);//Hell5 my name is hectick, n5t hectic 출력
		
		str = str.replace("hectic", "*");
		System.out.println(str); // Hell5 my name is *k, n5t * 출력
	}
}

 

replaceAll()

정규 표현식(regex, regular expression)과 일치하는 하위 문자열을 replacement로 바꾼다.

replaceAll(String regex, String replacement)
import java.io.*;

public class Main {
	public static void main(String[] args) {
		String str = "Hello my name is hectick, not hectic";
		
		str = str.replaceAll("hectic", "*");
		System.out.println(str); // Hello my name is *k, not * 출력
	}
}

 

replaceFirst()

정규 표현식(regex, regular expression)과 일치하는 첫 번째 하위 문자열을 replacement로 바꾼다.

replaceFirst(String regex, String replacement)
import java.io.*;

public class Main {
	public static void main(String[] args) {
		String str = "Hello my name is hectick, not hectic";
		
		str = str.replaceFirst("hectic", "*");
		System.out.println(str); // Hello my name is *k, not hectic 출력
	}
}

 

 

+ 현재 출력 예시로는 replace와 replaceAll의 차이점이 안보인다.

정규표현식은 일반 문자열로 표현할 수 없는것을 표현하는 개념인것 같은데, 정확히 이게 뭔지는 천천히 공부해서 정리해보도록 하겠다...!!