코딩 테스트

주요 String 메서드 모음

duhwan98 2025. 4. 3. 17:08

✅ 주요 String 메서드 모음

length() 문자열 길이 반환 "hello".length() → 5
charAt(index) 특정 위치의 문자 반환 "hello".charAt(1) → 'e'
substring(start, end) 부분 문자열 반환 "hello".substring(1, 4) → "ell"
indexOf(str) 특정 문자/문자열의 첫 번째 위치 반환 "hello".indexOf('l') → 2
lastIndexOf(str) 특정 문자/문자열의 마지막 위치 반환 "hello".lastIndexOf('l') → 3
contains(str) 특정 문자열 포함 여부 (true/false) "hello".contains("ll") → true
equals(str) 문자열 비교 (대소문자 구분 O) "hello".equals("Hello") → false
equalsIgnoreCase(str) 문자열 비교 (대소문자 구분 X) "hello".equalsIgnoreCase("Hello") → true
toUpperCase() 대문자로 변환 "hello".toUpperCase() → "HELLO"
toLowerCase() 소문자로 변환 "HELLO".toLowerCase() → "hello"
trim() 앞뒤 공백 제거 " hello ".trim() → "hello"
replace(old, new) 특정 문자/문자열 치환 "hello".replace('l', 'x') → "hexxo"
replaceAll(regex, new) 정규식 기반 치환 "a1b2c3".replaceAll("\\d", "*") → "a*b*c*"
split(regex) 특정 기준으로 문자열 분리 (배열 반환) "a,b,c".split(",") → ["a", "b", "c"]
startsWith(str) 특정 문자열로 시작하는지 확인 "hello".startsWith("he") → true
endsWith(str) 특정 문자열로 끝나는지 확인 "hello".endsWith("lo") → true
isEmpty() 문자열이 비어있는지 확인 "".isEmpty() → true
join(delimiter, elements...) 여러 문자열을 특정 문자로 결합 String.join("-", "a", "b", "c") → "a-b-c"
valueOf(data) 기본 타입을 문자열로 변환 String.valueOf(123) → "123"

✅ String vs StringBuilder vs StringBuffer 비교

  String StringBuilder StringBuffer
변경 가능 여부 ❌ (불변) ✅ (변경 가능) ✅ (변경 가능)
멀티쓰레드 안전성 ❌ (안전하지 않음) ❌ (안전하지 않음) ✅ (안전함 - 동기화 O)
속도 느림 (새 객체 생성) 가장 빠름 🚀 느림 (동기화 처리)
사용 목적 작은 문자열 조작 싱글쓰레드 환경에서 빠른 문자열 수정 멀티쓰레드 환경에서 안전한 문자열 수정

🔹 주요 메서드 정리 (StringBuilder & StringBuffer)

메서드 설명 예제
append(str) 문자열 끝에 추가 sb.append(" World")
insert(index, str) 특정 위치에 삽입 sb.insert(5, " Java")
delete(start, end) 특정 범위 삭제 sb.delete(5, 10)
replace(start, end, str) 특정 범위 문자열 변경 sb.replace(5, 10, "Python")
reverse() 문자열 뒤집기 sb.reverse()
length() 문자열 길이 반환 sb.length()