Recent Posts
Recent Comments
Link
06-30 12:53
Today
Total
관리 메뉴

삶 가운데 남긴 기록 AACII.TISTORY.COM

JAVA String 처리 본문

DEV&OPS/Java

JAVA String 처리

ALEPH.GEM 2022. 4. 11. 13:50

바이트 배열을 문자열로 변환

문자열은 본래 바이트(byte/char)의 배열로 되어있습니다.

자바에서는 이를 클래스나 기본 데이터 타입처럼 String 을 다룰 수 있습니다.

public class ByteToString {

	public static void main(String[] args) {
		byte[] bytes = {72, 101, 108, 108, 111, 32, 74, 97, 118, 97 }; //Hello Java
		String str1 = new String(bytes);
		System.out.println(str1);
		String str2 = new String(bytes, 6, 4);	//6번째 인덱스부터 길이가 4만큼
		System.out.println(str2);
	}

}

실행 결과

Hello Java
Java

영어는 1바이트(아스키코드)로 표현되지만 한글의 경우 2바이트 이상으로 표현하기 때문에 문자 수와 바이트 길이에 신경을 써야 합니다.

캐리지리턴(\r)과 라인피드(\n)같은 기호들도 바이트 배열에서 1byte를 차지합니다.

 

charAt()

인수로 전달한 인덱스의 문자(character)를 리턴합니다.

public class StringCharAt {

	public static void main(String[] args) {
		String ssn = "991109-1234567";	//가상 주민번호
		char gender = ssn.charAt(7);	//주민번호 뒷자리의 첫 문자를 획득
		switch(gender){
			case '1':
				System.out.println("남자");
				break;
			case '2':
				System.out.println("여자");
				break;
		}
	}
}

 

equals(), equalsIgnoreCase()

== 연산자도 문자열을 비교할 수 있지만 참조된 주소가 다르다면 문자열 내용이 같아도 false를 리턴합니다.

그래서 참조된 주소와 관계없이 문자열의 내용을 비교하는 equals 메서드를 제공합니다.

equalsIgnoreCase()는 대소문자를 무시해서 비교하는 메서드 입니다.

equals()는 Object에서는 메모리 번지 비교 메소드 지만 String클래스에서 오버라이딩 한 것입니다.

public class StringEquals {

	public static void main(String[] args) {
		String strVar1 = new String("aacii");
		String strVar2 = "aacii";
		if(strVar1 == strVar2) {
			System.out.println("같은 객체 참조");
		}else {
			System.out.println("다른 객체 참조");
		}
		if(strVar1.equals(strVar2)) {
			System.out.println("문자열이 같음");
		}
		if(strVar1.equalsIgnoreCase("AACII")) {
			System.out.println("대소문자를 무시하고 같음");
		}
	}

}

 

getBytes() 

문자열을 바이트 배열로 변환합니다.

인수로 한글 인코딩 방식을 지정해줄수 있습니다.

import java.io.UnsupportedEncodingException;

public class StringGetBytes {

	public static void main(String[] args) {
		String str = "한글ab3";
		byte[] bytes1 = str.getBytes();
		System.out.println("bytes1.length:"+bytes1.length);
		
		String str1 = new String(bytes1);
		System.out.println("bytes1 to String:"+str1);
		
		try {
			byte[] bytes2 = str.getBytes("EUC-KR");
			System.out.println("bytes2.length:"+bytes2.length);
			String str2 = new String(bytes2, "EUC-KR");
			System.out.println("bytes2 to String:"+str2);
			
			byte[] bytes3 = str.getBytes("UTF-8");
			System.out.println("bytes3.length:"+bytes3.length);
			String str3 = new String(bytes3, "UTF-8");
			System.out.println("bytes3 to String:"+str3);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
	}

}

 

indexOf(문자열)

인수로 전달한 문자열이 시작되는 인덱스를 리턴합니다. 

여기서 인덱스는 바이트 배열의 인덱스가 아니고 몇번째 글자인지를 나타냅니다.

시작 인덱스는 0부터 시작합니다.

만약 해당 문자열이 없다면 -1을 리턴합니다.

public class StringIndexOf {

	public static void main(String[] args) {
		String subject = "자바 프로그래밍";
		int location = subject.indexOf("프로그래밍");
		System.out.println(location);
		if(subject.indexOf("스크립트") == -1) {
			System.out.println("문자열이 없습니다.");
		}else {
			System.out.println(location);
		}
	}

}

 

length()

공백을 포함한 문자의 수를 리턴합니다.

문자의 인덱스가 7까지 라면 length()는 8을 리턴합니다.

public class StringLength {

	public static void main(String[] args) {
		String subject = "자바 프로그램";
		int length = subject.length();
		System.out.println(length);
	}

}

 

replace()

문자열(인수1)을 다른 문자열(인수2)로 교체합니다.

public class StringReplace {

	public static void main(String[] args) {
		String oldStr ="old text";
		String newStr = oldStr.replace("old", "new");
		System.out.println(oldStr);
		System.out.println(newStr);
	}

}

실행결과:

old text
new text

 

substring()

주어진 문자열중 일부를 시작인덱스부터 종료인덱스까지 잘라내어 리턴합니다.

종료 인덱스는 생략 가능합니다.

public class StringSubstring {

	public static void main(String[] args) {
		String ssn = "990815-1234567";
		String firstNum = ssn.substring(0, 6);
		System.out.println(firstNum);
		String secondNum = ssn.substring(7);
		System.out.println(secondNum);
	}

}

 

toLowerCase(), toUpperCase()

주어진 알파벳 문자열을 소문자로(lowerCase) 혹은 대문자로(UpperCase)로 변환합니다.

public class StringCase {

	public static void main(String[] args) {
		String str1 = "Java Program";
		String str2 = "JAVA Program";
		System.out.println(str1.equals(str2));	//false
		
		String lowerStr1 = str1.toLowerCase();
		String lowerStr2 = str2.toLowerCase();
		System.out.println(lowerStr1.equals(lowerStr2));	//true
		
		System.out.println(str1.equalsIgnoreCase(str2)); 	//true
	}

}

 

trim()

문자열의 앞뒤 공백을 제거한 문자열을 리턴합니다.

문자열의 중간 공백은 제거 되지 않습니다.

그리고 원래 문자열의 공백이 제거되지는 않습니다.

public class StringTrim {

	public static void main(String[] args) {
		String str1 = "  12 34  ";
		System.out.println(str1.trim());
		System.out.println(str1);
	}

}

 

valueOf()

기본 데이터 타입의 데이터를 문자열로 변환해줍니다.

public class StringValueOf {

	public static void main(String[] args) {
		String str1 = String.valueOf(10.5);
		String str2 = String.valueOf(true);
		System.out.println(str1);
		System.out.println(str2);
	}

}

 

split()

문자열을 구분자(delimiter)로 분리해서 배열로 리턴해줍니다.

보통 구분 기호를 인수로 전달하지만, 정규표현식을 인수로 전달할 수도 있습니다.

public class StringSplit {

	public static void main(String[] args) {
		String text ="홍길동1&홍길동2,홍길동3,홍길동4-홍길동5";
		String[] names = text.split("&|,|-");
		for(String name : names) {
			System.out.println(name);
		}
	}

}

결과:

홍길동1
홍길동2
홍길동3
홍길동4
홍길동5

 

String.concat()과 + (문자열 연결 연산자)

Java에서 String concat() 메서드와 + 연산자는 문자열을 합치는 기능입니다.

하지만 내부적으로는 다른 방식으로 동작합니다. 

concat()의 경우 String data 가 합쳐지기 전 메모리 주소(힙 영역)와 다른 곳에 합쳐질 문자열을 new String()을 통해서 새로운 메모리 주소(힙 영역)에 할당하여 저장합니다.

+ 연산자의 경우 문자열을 StringBuilder 클래스의 인스턴스로 변경하여 기존 합쳐지기 전 메모리 주소(힙영역)에 합쳐질 문자열을 추가해서 저장합니다.

따라서 문자열의 값을 비교하는 작업을 할 때 저장된 String의 메모리 주소가 다를 수 있으니 신경 써줄 필요가 있습니다.

 

String과 String builder

String으로 생성한 데이터는 상수 영역(constant)에 저장되어 한 번 정의하면 변하지 않는 문자 데이터에 적합합니다.

String은 클래스 이지만 기본 데이터 타입 처럼 사용할 수 있습니다.

String builder 는 값의 변화가 빈번한 문자 데이터를 다룰 때 효율적입니다. 

 

String builder 와 String buffer

String buffer는 synchronise 되어 있어 string builder에 비해 멀티 스레드 환경에서 안전합니다.

네트워크 통신 관련 프로그램에서는 거의 멀티스레드 환경이므로 String buffer로 작업하시는 것을 추천합니다.

public class StringBufferEX {

	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append("java");
		sb.append("Program");
		System.out.println(sb.toString());
	}

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

DEV

 

728x90

'DEV&OPS > Java' 카테고리의 다른 글

Arrays 클래스  (0) 2022.04.12
java.util.regex.Pattern 클래스  (0) 2022.04.12
System 클래스  (0) 2022.04.07
java.util.Objects 클래스  (0) 2022.04.07
자바 API , Object 클래스  (0) 2022.04.07