본문 바로가기
Java

[Java] String 다루기(1)

by happyhelen 2021. 7. 22.

순서는 내맘대로~~!

 

[1] 문자열 추출하는 substring

[2] 문자열 잘라서 배열에 넣는 split

[3] 문자/문자열 대체하는 replace/replaceAll

[4] 원하는 문자/문자열의 첫 시작 인덱스 반환하는 indexOf

[5] 원하는 인덱스의 char 반환하는 charAt

[6] 특정 문자/문자열을 포함하는지 불린 리턴하는 contains

 

public class AllaboutString {

	public static void main(String[] args) {
		String number = "112233-123-1234-5678";
		String name = "*Choi*Jun*";
		String hello = "I'm glad to see you";
		
		//[1] 문자열 추출
		String s1 = number.substring(2); // String.substring(int beginIndex)
		System.out.println(s1);
		String s2 = number.substring(3, 7); // String.substring(int beginIndex, int endIndex)
		System.out.println(s2);
		
		//[2] 문자열 자르고 배열에 넣기
		String[] s3 = name.split("\\*"); // String.split(String regex) 특수문자는 "\\*"로 검색
		System.out.println(s3); // (!) 참조하고 있기 때문에 주소값 출력됨
		for(int i=0; i<s3.length; i++) { // (!) regex 문자열 기준 양옆으로 잘라서, 해당 regex로 시작할 경우 첫번째 배열값은 공백
			System.out.println(s3[i]); // 배열변수명[int]로 접근
		}
		
		//[3] 대체하기
		String s4 = number.replace('-', '#'); // 항상 변수에 넣는 습관 들이기, 변수에 넣지 않으면 변화X
		System.out.println(s4); 
		String s5 = number.replace("123","999");
		System.out.println(s5);
		String s6 = number.replaceAll("[123]", "00"); // replaceAll은 정규식 사용가능
		System.out.println(s6);
		
		//[4] 문자열 중 해당하는 char문자의 처음 시작 index 반환
		int index1 = hello.indexOf("glad"); // 숫자, 문자, 문자열 다 가능/ 없으면 -1반환
		System.out.println(index1);
		int index2 = hello.indexOf(5, 'm'); // 두 매개값 순서를 바꿔도됨
		System.out.println(index2);
		
		//[5] 해당index의 char 반환
		char chr1 = hello.charAt(4);
		System.out.println(chr1);
		
		//[6] 특정 문자/문자열을 포함하는지 T/F
		boolean bln1 = name.contains("un");// '문자'는 안됨, charSequence 
		System.out.println(bln1);
		

	}

}