Java/자료구조
[Java][코딩테스트] String 빈출 함수 - charAt, toCharArray, subString, indexOf
s.a
2022. 7. 3. 14:43
반응형
1. charAt(n)
1) 문자열의 n번째 index의 문자를 구할 수 있다.
String str = "가나다라마바사";
System.out.println(str.charAt(0));// 가
2) 문자열의 n번째 index의 문자(char)를 int로 반환할 수 있다.
String str = "12345678";
int num1 = str.charAt(1)-'0';
int num2 = str.charAt(2)-'0';
System.out.println(num1);// 2
System.out.println(num2);// 3
2. toCharArray
- 문자열을 char[]로 반환해준다.
String str = "12345678";
char[] array = str.toCharArray();
for(int i = 0; i < array.length ; i++) {
System.out.println("array["+ i +"] :"+ array[i]);
}
/* console :
array[0] :1
array[1] :2
array[2] :3
array[3] :4
array[4] :5
array[5] :6
array[6] :7
array[7] :8
*/
3. substring
1) substring(BeginIndex, endIndex)
- 문자열의 BeginIndex번째 문자부터 endIndex번째 문자의 앞까지의 문자를 잘라서 보여준다.
String str = "abcdefgh";
String result1 = str.substring(0, 2);// 0~1번째 문자를 가져온다.
String result2 = str.substring(2, 5);// 2~4번째 문자를 가져온다.
System.out.println(result1);// ab
System.out.println(result2);// cde
2) substring(Index)
- index번째 문자부터 문자열의 끝까지를 출력한다.
String str = "abcdefgh";
String result = str.substring(2); // 2번째 문자부터 끝까지 출력
System.out.println(result); // cdefgh
4. indexOf(String str)
1) indexOf(String str)
- 비교하려는 문자열 중 str과 동일한 문자열이 시작하는 idx를 출력한다.
- 만약 str과 동일한 문자가 존재하지 않는다면 -1을 리턴한다.
String str = "natural banana";
int idx1 = str.indexOf("na"); // str에서 na로 시작하는 가장 첫 index를 구함
int idx2 = str.indexOf("oa"); // str에서 oa로 시작하는 가장 첫 index를 구함
System.out.println(idx1);// 0
System.out.println(idx2);// -1
2) indexOf(String str, int fromIdx)
- 비교하려는 문자열의 fromIdx번째의 문자부터 str과 동일한 문자열이 시작하는 idx를 출력한다.
String str = "natural banana";
int idx1 = str.indexOf("na", 4); // str에서 4번째 문자부터 na로 시작하는 문자열의 index를 구함
int idx2 = str.indexOf("na", 10); // str에서 10번째 문자부터 na로 시작하는 문자열의 index를 구함
int idx3 = str.indexOf("na", 11); // str에서 11번째 문자부터 na로 시작하는 문자열의 index를 구함
System.out.println(idx1); // 10
System.out.println(idx2); // 10
System.out.println(idx3); // 12