728x90
반응형
SMALL
| 메서드 | 설명 | 예시 |
| `length()` | 문자열 길이 | `"abc".length() → 3` |
| `charAt(i)` | i번째 문자 반환 | `"abc".charAt(1) → 'b'` |
| `substring(a,b)` | 부분 문자열 추출 | `"abcde".substring(1,3) → "bc"` |
| `equals()` | 문자열 비교 | `"abc".equals("abc") → true` |
| `equalsIgnoreCase()` | 대소문자 무시 비교 | `"Abc".equalsIgnoreCase("abc")` |
| `contains()` | 포함 여부 확인 | `"apple".contains("pp")` |
| `indexOf()` | 첫 등장 위치 찾기 | `"banana".indexOf("a") → 1` |
| `startsWith()` | 접두사 확인 | `"file.txt".startsWith("file")` |
| `endsWith()` | 접미사 확인 | `"file.txt".endsWith(".txt")` |
| `replace()` | 문자열 치환 | `"apple".replace("p","b")` |
| `toUpperCase()` | 대문자로 변환 | `"java".toUpperCase()"` |
| `toLowerCase()` | 소문자로 변환 | `"JAVA".toLowerCase()"` |
| `split()` | 문자열 나누기 | `"a,b,c".split(",")` |
| `trim()` | 앞뒤 공백 제거 | `" hello ".trim() → "hello"` |
1. 문자열 길이 구하기 - `length()`
String str = "Hello";
int len = str.length(); // 5
- 문자열에 포함된 문자의 개수를 반환
- 공백도 문자로 포함됨에 유의!
2. 문자 하나 가져오기 - `charAt(int index)`
String str = "Java";
char c = str.charAt(1); // 'a'
- 문자열에서 특정 인덱스의 문자 반환
- 인덱스는 0부터 시작하며, 범위를 벗어나면 `StringIndexOutOfBoundsException` 발생
3. 부분 문자열 추출 - `substring(int start, int end)`
String str = "HelloWorld";
String sub = str.substring(0, 5); // "Hello"
- `start`부터 `end-1`까지의 문자열 반환
- `end`는 포함되지 않음
- `substring(start)` 형태로 끝까지 잘라낼 수도 있음
4. 문자열 비교 - `equals()`, `equalsIgnoreCase()`
"abc".equals("abc") // true
"abc".equals("ABC") // false
"abc".equalsIgnoreCase("ABC") // true
- `==` 연산자는 주소 비교임. 문자열 값 비교는 반드시 `equals()` 사용
- 대소문자 무시하려면 `equalsIgnoreCase()`
5. 포함 여부 확인 - `contains(CharSequence s)`
"HelloWorld".contains("World") // true
- 특정 문자열이 포함되어 있는지 여부를 boolean으로 반환
6. 특정 문자열 위치 찾기 - `indexOf()`
"banana".indexOf("a") // 1
"banana".indexOf("z") // -1
"banana".indexOf(char/str, fromIndex) // 다음 등장 위치를 계속 탐색
- 첫 번째로 등장하는 위치 반환
- 찾는 문자열이 없으면 `-1` 반환
7. 문자열 시작/끝 확인 - `startsWith()`, `endsWith()`
"file.txt".startsWith("file") // true
"file.txt".endsWith(".txt") // true
- 접두사/접미사 확인할 때 유용
8. 문자열 치환 - `replace()`
"apple".replace("p", "b") // "abble"
- 모든 해당 문자열을 다른 문자열로 바꿔줌
9. 대소문자 변환 - `toUpperCase()`, `toLowerCase()`
"Java".toUpperCase() // "JAVA"
"Java".toLowerCase() // "java"
- 단어 정규화, 비교용 등으로 자주 사용
10. 문자열 나누기 - `split(String regex)`
String[] arr = "a,b,c".split(",");
System.out.println(Arrays.toString(arr)); // [a, b, c]
- 정규표현식 기반으로 문자열을 쪼개 배열로 반환
- .split("\\.") 같이 특수문자는 이스케이프 필요
11. 앞뒤 공백 제거 - `trim()`
" hello ".trim() // "hello"
- 문자열 양쪽의 공백만 제거함 (중간 공백은 제거하지 않음)
728x90
반응형
LIST