[Java] 문자열 다루기

은현수·2024년 6월 26일

Intro

코딩테스트 프로그래머스 lv.0 을 문자열 부분을 푸는 도중 문자열에 관한 부분을 정리해보고자 한다.

특정 문자 위치 찾기

1. 앞에서 부터 찾기 - indexOf()

indexOf() 는 특정 문자나 문자열이 앞에서부터 처음 발견되는 인덱스를 반환하며 만약 찾지 못했을 경우 "-1"을 반환한다.

public class IndexOfTest{
    public static void main(String[] args){

        String indexOfTestOne = "Hello world";
        String indexOfTestTwo = "         Hello world         ";     

        System.out.println( indexOfTestOne.indexOf("o") );  // 4
        System.out.println( indexOfTestOne.indexOf("x") );  // -1
        System.out.println( indexOfTestOne.indexOf("o",5) );  // 7
        System.out.println( indexOfTestTwo.indexOf("o") );  // 13
        System.out.println( indexOfTestTwo.indexOf("el") );  // 10

    }
}

.indexOf( "찾을 특정 문자" , "시작할 위치" ) 이런식으로 사용해 주면된다.

2. 뒤에서 부터 찾기 - lastIndexOf()

lastindexOf() 는 특정 문자나 문자열이 뒤에서부터 처음 발견되는 인덱스를 반환하며 만약 찾지 못했을 경우 "-1"을 반환한다.

public class IndexOfTest{
    public static void main(String[] args){

        String indexOfTestOne = "Hello world";

        System.out.println( indexOfTestOne.lastIndexOf("o") );  // 7
        System.out.println( indexOfTestOne.lastIndexOf("x") );  // -1
        System.out.println( indexOfTestOne.lastIndexOf("o",5) );  // 4

    }
}

.indexof()와 사용법은 같으며, 주의사항으로는 뒤에서부터의 값을 반환하는 것이 아닌 앞에서 부터의 값을 반환한다.

문자열 자르기

1. subString()

substring() 함수는 시작지점과 끝지점을 파라미터로 전달받아서 문자열을 자르게 된다.

substring(시작지점, 끝지점) 이런식으로 사용하면 된다.

public static void main(String[] args) {		
	String str = "abcdefg12345";
	System.out.println("substring(5) : " + str.substring(5)); //fg12345
	System.out.println("substring(0,1) : " + str.substring(0,1)); // a
	System.out.println("substring(1,2) : " + str.substring(1,2)); // b
	System.out.println("substring(2,3) : " + str.substring(2,3)); // c
	System.out.println("substring(2,10) : " + str.substring(2,10)); // cdefg123
}

2. split()

split() 함수는 특정 문자열을 파라미터로 받아서 해당 문자열을 기준으로 문자열을 잘라서 배열에 넣어주는 기능을 한다. String 의 멤버함수이다.

public static void main(String[] args) {		
	String str = "ABC,EE,QQ1,5112";
	String arr[] = str.split(",");
	for(String cut : arr) {
		System.out.println(cut);
	}		
} 
//ABC
//EE
//QQ1
//5112

이때, split의 두번째 파라미터로 -1 을 입력해주면 문자열이 공백으로 끝날때, 마지막에 공백도 얻을 수 있다.

문자열 치환

1. replace()

replace( ) 메소드는 첫 번째 매개값인 문자열을 찾아 두 번째 매개값인 문자열로 대치한 새로운 문자열을 생성하고 리턴한다.

String oldStr = "자바 프로그래밍";
String newStr = oldStr.replace("자바", "JAVA"); //java 프로그래밍

참고 블로그

https://hijuworld.tistory.com/78
https://mine-it-record.tistory.com/124
https://hongong.hanbit.co.kr/java-%EC%9E%90%EB%B0%94-%EB%AC%B8%EC%9E%90%EC%97%B4%EC%9D%84-%EB%8B%A4%EB%A3%A8%EB%8A%94-string-%ED%81%B4%EB%9E%98%EC%8A%A4-%EB%A9%94%EC%86%8C%EB%93%9C-%EC%B4%9D%EC%A0%95%EB%A6%AC/

profile
백엔드 개발자

0개의 댓글