문자열 검색(String Search)

BaeSeBin·2025년 1월 7일

😊String.indexOf(char)

주어진 문자가 문자열에서 처음 등장하는 위치를 반환함. 문자가 문자열에 없으면 -1을 반환함.
String str = "HelloWorld";
char ch = 'o';

int index = str.indexOf(ch);
System.out.println(index); // 출력: 4

😊String.lastIndexOf(char)

주어진 문자가 문자열에서 마지막으로 등장하는 위치를 반환함. 문자가 문자열에 없으면 -1을 반환함.
String str = "HelloWorld";
char ch = 'o';

int index = str.lastIndexOf(ch);
System.out.println(index); // 출력: 7

😊String.contains(CharSequence)

문자열이 특정 문자 또는 문자열을 포함하고 있는지 확인함. 반환 값은 boolean임.
String str = "HelloWorld";
String target = "World";

boolean contains = str.contains(target);
System.out.println(contains); // 출력: true

😊String.charAt(index)

특정 인덱스에 있는 문자를 가져옴.
인덱스가 범위를 벗어나면 IndexOutOfBoundsException이 발생함.
String str = "HelloWorld";

char ch = str.charAt(4); // 4번째 문자 가져오기 (0부터 시작)
System.out.println(ch); // 출력: o

0개의 댓글