'javareplace'에 해당되는 글 1건

  1. 2023.03.14 JAVA 문자열 공백 제거, 중간 공백 제거
Java2023. 3. 14. 16:05

trim()으로 앞 뒤의 공백을 제거할수는 있지만,

중간의 공백을 제거해야할 일이 많이 있다.

그런 경우에 여러가지 방법이 있음'-'

1. replaceALL 을 이용

가장 쓰기 편한 방법같다..

 

public class SimpleTesting {

	public static void main(String[] args) {
		String str = "DEER LOVE DEER HANDSOME";
		String result = str.replaceAll("\\s+","");
		System.out.println(result);
	}
}

 

 

2. Apache의 StringUtils를 활용하여 공백 제거하기

StringUtils 클래스에 deleteWhiteSpace 메소드가 있다.

 

import org.apache.commons.lang3.StringUtils;

public class SimpleTesting {

	public static void main(String[] args) {
		String str = "DEER LOVE DEER HANDSOME";
		String result = StringUtils.deleteWhitespace(str);
		System.out.println(result);
	}
}

 

 

 

3. 정규식을 활용해서 Pattern 및 Matcher로 제거

물론 replaceAll과 정규식 조합'-'

 

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SimpleTesting {

	public static void main(String[] args) {
		String str = "DEER LOVE DEER HANDSOME";
		Pattern p = Pattern.compile("[\\s]");
        Matcher m = p.matcher(str);
        String result = m.replaceAll("");
		System.out.println(result);
	}
}

 

 

 

4. 공백만 제거하고 \n, \t는 제거 안하기

replace를 활용한다.

 

public class SimpleTesting {

	public static void main(String[] args) {
		String str = "DEER LOVE DEER HANDSOME";
        String result = str.replace(" ", "");
		System.out.println(result);
	}
}

 

 

5. Apache를 사용하여 공간 제거

StringUtils의 replace를 활용한다.

 

import org.apache.commons.lang3.StringUtils;

public class SimpleTesting {

	public static void main(String[] args) {
		String str = "DEER LOVE DEER HANDSOME";
        String result = StringUtils.replace(str, " ", "");
		System.out.println(result);
	}
}

 

 

 

'Java' 카테고리의 다른 글

[intelliJ] 실시간 소스 수정 반영  (0) 2023.03.14
JAVA 만 나이 계산하여 리턴하기  (0) 2023.03.14
JAVA 이메일 체크 정규식  (0) 2023.03.13
JAVA 문자열 앞자리 0 제거  (0) 2023.03.12
String을 Json으로 변환 예제  (2) 2023.03.12
Posted by 사슴영혼'-'