코딩/Java

[Java] String 관련 메서드

americanoallday 2025. 4. 14. 12:07

🔤 문자열 생성 & 변환

메서드
설명 예시
String.valueOf(숫자) 숫자 → 문자열 변환 String.valueOf(123)"123"
Integer.toString(숫자) 숫자 → 문자열 Integer.toString(10)"10"
String str = "abc"; 문자열 생성 "abc"

🔍 문자열 내용 확인

메서드
설명 예시
length() 문자열 길이 "hello".length()5
charAt(int index) 특정 문자 얻기 "cat".charAt(1)'a'
contains(String s) 포함 여부 "hello".contains("ell")true
startsWith(String s) 접두사 확인 "hello".startsWith("he")true
endsWith(String s) 접미사 확인 "hello".endsWith("lo")true
indexOf(String s) 처음 등장 위치 "banana".indexOf("a")1
lastIndexOf(String s) 마지막 등장 위치 "banana".lastIndexOf("a")5
isEmpty() 비어있는지 확인 "".isEmpty()true

✂️ 문자열 자르기 & 추출

메서드 설명 예시
substring(int begin) 해당 인덱스부터 끝까지 자르기 "hello".substring(2)"llo"
substring(int begin, int end) 구간 자르기 (end는 포함 안 됨) "hello".substring(1, 4)"ell"
split(String regex) 특정 기준으로 나누기 "a,b,c".split(",")["a", "b", "c"]

🧼 문자열 변형

메서드
설명 예시
toUpperCase() 대문자로 변환 "hello".toUpperCase()"HELLO"
toLowerCase() 소문자로 변환 "HELLO".toLowerCase()"hello"
trim() 앞뒤 공백 제거 " hello ".trim()"hello"
replace(a, b) 문자 or 문자열 치환 "apple".replace("p", "b")"abble"
replaceAll(regex, repl) 정규표현식 기반 치환 "a1b2c3".replaceAll("[0-9]", "")"abc"

🔁 문자열 비교

메서드
설명 예시
equals(String s) 정확히 같은지 비교 "hi".equals("hi")true
equalsIgnoreCase(String s) 대소문자 무시하고 비교 "Hi".equalsIgnoreCase("hi")true
compareTo(String s) 사전순 비교 (같으면 0) "a".compareTo("b") → 음수

 

'코딩 > Java' 카테고리의 다른 글

[Java] Integer란  (0) 2025.04.14
[Java] StringBuilder란  (0) 2025.04.14
default 메서드란  (0) 2025.04.03
Java 6 : Map, Hash, HashTable  (1) 2025.02.07
Java 5 : 객체지향(OOP : Object-Oriented-Programming), 추상화, 인터페이스  (0) 2025.02.06