문자열에서 자주 쓰는 메서드 및 예제 정리

chocobiv·2024년 11월 15일
post-thumbnail

📌 문자열에서 자주 쓰는 메서드

메소드설명예시
contains(String s)특정 문자열이 포함되어 있는지 검사"hello".contains("ell") → true
equals(String s)두 문자열이 완전히 같은지 비교"abc".equals("abc") → true
equalsIgnoreCase(String s)대소문자 무시하고 문자열 비교"abc".equalsIgnoreCase("ABC") → true
charAt(int index)특정 인덱스 위치의 문자 가져오기"apple".charAt(1) → 'p'
substring(int start, int end)문자열의 일부분 잘라내기 (end는 포함 안 함)"abcdef".substring(1,4) → "bcd"
startsWith(String prefix)특정 문자열로 시작하는지 검사"hello".startsWith("he") → true
endsWith(String suffix)특정 문자열로 끝나는지 검사"world".endsWith("ld") → true
indexOf(String s)특정 문자열이 처음 등장하는 인덱스 찾기"banana".indexOf("na") → 2
lastIndexOf(String s)특정 문자열이 마지막으로 등장하는 인덱스 찾기"banana".lastIndexOf("na") → 4
length()문자열 길이 반환"hello".length() → 5
toLowerCase()문자열을 모두 소문자로 변환"HeLLo".toLowerCase() → "hello"
toUpperCase()문자열을 모두 대문자로 변환"HeLLo".toUpperCase() → "HELLO"
replace(CharSequence target, CharSequence replacement)문자열 일부를 다른 문자열로 대체"apple".replace("p", "b") → "abble"
split(String regex)특정 구분자를 기준으로 문자열을 쪼개 배열로 반환"a,b,c".split(",") → ["a", "b", "c"]
trim()앞뒤 공백 제거" hello ".trim() → "hello"




좀 더 빠른 이해를 위해 간단한 활용 예제를 알아보자.

💡 메서드 사용 예제

1. split() — 쉼표로 구분된 데이터 분리하기

public class SplitExample {
    public static void main(String[] args) {
        String data = "apple,banana,orange";
        String[] fruits = data.split(",");

        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

출력

apple
banana
orange

👉 자주 나오는 문제: "띄어쓰기/쉼표/콜론(:)으로 단어 나누기"
→ 무조건 split() 사용!


2. substring() — 주민등록번호 생년월일 추출

public class SubstringExample {
    public static void main(String[] args) {
        String ssn = "991231-1234567";
        String birth = ssn.substring(0, 6);		// 0~5 인덱스
        System.out.println("생년월일: " + birth);
    }
}

출력

생년월일: 991231

👉 특정 패턴(예: 앞 6자리, 뒷 7자리) 뽑을 때 substring() 사용


3. charAt() — 문자열 한 글자씩 출력하기

public class CharAtExample {
    public static void main(String[] args) {
        String word = "hello";

        for (int i = 0; i < word.length(); i++) {
            System.out.println(word.charAt(i));
        }
    }
}

출력

h
e
l
l
o

👉 문자 하나하나 순회할 때 꼭 필요
(특히, 팰린드롬(회문) 검사할 때 많이 사용)


4. replace() — 문자열에서 문자 바꾸기

public class ReplaceExample {
    public static void main(String[] args) {
        String text = "apple pie";
        String result = text.replace("pie", "juice");

        System.out.println(result);
    }
}

출력

apple juice

👉 문자열 특정 부분을 바꿀 때 사용
(예를 들어 욕설 필터링할 때도 replace() 많이 사용함)


5. indexOf() — 단어 찾기

public class IndexOfExample {
    public static void main(String[] args) {
        String sentence = "I love programming";

        if (sentence.indexOf("love") != -1) {
            System.out.println("사랑이 있네요!");
        }
    }
}

출력

사랑이 있네요!

👉 어떤 단어가 포함되어 있는지 직접 위치를 알아내고 싶을 때 사용


6. trim() — 입력값 전처리

import java.util.Scanner;

public class TrimExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        System.out.println("공백 제거 후: " + input.trim());
    }
}

입력
" hello "

출력

공백 제거 후: hello

👉 사용자 입력 받을 때 (Scanner.nextLine() 시) 꼭 trim() 해서 앞뒤 공백 제거하는 습관 들이는 게 좋음.


7. startsWith() — 특정 문자열로 시작하는지 확인

public class StartsWithExample {
    public static void main(String[] args) {
        String url = "https://openai.com";

        if (url.startsWith("https")) {
            System.out.println("보안 연결입니다.");
        }
    }
}

출력

보안 연결입니다.

👉 문자열이 특정 접두어로 시작하는지 판단할 때 유용.
예: URL이 https, 전화번호가 010, 파일명이 IMG_ 등.


8. endsWith() — 특정 문자열로 끝나는지 확인

public class EndsWithExample {
    public static void main(String[] args) {
        String filename = "document.pdf";

        if (filename.endsWith(".pdf")) {
            System.out.println("PDF 파일입니다.");
        }
    }
}

출력

PDF 파일입니다.

👉 확장자 검사, 특정 패턴으로 끝나는지 판단할 때 많이 사용.


9. lastIndexOf() — 특정 문자가 마지막으로 나타나는 위치

public class LastIndexOfExample {
    public static void main(String[] args) {
        String path = "/usr/local/bin/java";

        int lastSlash = path.lastIndexOf("/");
        System.out.println("마지막 슬래시 위치: " + lastSlash);
    }
}

출력

마지막 슬래시 위치: 16

👉 문자열에서 마지막으로 나타나는 위치가 필요할 때 사용.
예: 파일 경로 분리, 확장자 추출 등에 자주 등장


10. length() — 문자열의 길이 구하기

public class LengthExample {
    public static void main(String[] args) {
        String text = "Hello, world!";
        System.out.println("문자열 길이: " + text.length());
    }
}

출력

문자열 길이: 13

👉 문자열에 포함된 문자 수(공백 포함)를 구할 수 있음.
문자열 순회, 배열 생성 등 기초 중의 기초 메소드!


11. toLowerCase() / toUpperCase() — 대소문자 변환

public class CaseConversionExample {
    public static void main(String[] args) {
        String word = "HeLLo WoRLd";

        System.out.println(word.toLowerCase());
        System.out.println(word.toUpperCase());
    }
}

출력

hello world
HELLO WORLD

👉 대소문자를 통일해서 비교하거나 출력 포맷을 맞출 때 자주 사용됨.
입력값이 YES, yes, YeS 등 다양하게 들어올 때 유용!

profile
공부하는 velog

0개의 댓글