게으른 개발자의 끄적거림

String Method 간단 예제(substring, replace, indexOf 등)

끄적잉 2023. 3. 29. 21:39
반응형

Java String 클래스는 문자열을 다루는 다양한 메서드를 제공한다. 메서드들의 간단한 예제를 보자

 

1. length(): 문자열의 길이를 반환

 

String str = "Hello World!";
int length = str.length(); // length = 12

 

 

2. charAt(int index): 주어진 인덱스에 해당하는 문자를 반환

 

String str = "Hello World!";
char c = str.charAt(1); // c = 'e'

 

 

3. substring(int beginIndex, int endIndex): 주어진 범위에 해당하는 부분 문자열을 반환

 

String str = "Hello World!";
String sub = str.substring(0, 5); // sub = "Hello"

 

 

4. indexOf(String str): 주어진 문자열이 처음으로 등장하는 인덱스를 반환

 

String str = "Hello World!";
int index = str.indexOf("World"); // index = 6

 

 

5. toUpperCase(): 모든 문자를 대문자로 바꾸어 반환

 

String str = "Hello World!";
String upperStr = str.toUpperCase(); // upperStr = "HELLO WORLD!"

 

 

6. toLowerCase(): 모든 문자를 소문자로 바꾸어 반환

 

String str = "Hello World!";
String lowerStr = str.toLowerCase(); // lowerStr = "hello world!"

 

 

7. trim(): 문자열의 앞뒤 공백을 제거한 후 반환

 

String str = "   Hello World!   ";
String trimmedStr = str.trim(); // trimmedStr = "Hello World!"

 

 

8. replace(char oldChar, char newChar): 주어진 문자열에서 oldChar를 newChar로 대체한 새로운 문자열을 반환

 

String str = "Hello World!";
String replacedStr = str.replace('o', '0'); // replacedStr = "Hell0 W0rld!"

반응형

'게으른 개발자의 끄적거림' 카테고리의 다른 글

Mixed content 해결 방법 (feat. 타 블로그)  (0) 2023.04.03
URL 인코딩/디코딩  (0) 2023.03.30
향상된 for문 예제  (0) 2023.03.27
https에서 http 호출하는 방법  (0) 2023.03.22
HTTP란?  (0) 2023.03.16