문제
내가 작성한 정답
class Solution {
public int solution(String myString, String pat) {
return myString.toLowerCase().contains(pat.toLowerCase()) ? 1:0;
}
}
다른 사람들의 정답
class Solution {
public int solution(String myString, String pat) {
int answer = 0;
String str = myString.toLowerCase();
String str2 = pat.toLowerCase();
if (str.indexOf(str2) != -1) {
return 1;
}
return 0;
}
}
indexOf
: indexOf 메서드는 찾고자 하는 요소가 존재하면 해당 요소의 첫 번째 인덱스를 반환하고 요소가 존재하지 않으면 -1을 반환한다. 문자열이나 리스트에서 특정 요소의 위치를 찾을 때 사용한다.
- String 클래스의 indexOf 메서드
// 문자(char)의 인덱스 찾기
int index = str.indexOf(char ch);
// 문자열(String)의 인덱스 찾기
int index = str.indexOf(String str);
// 시작 인덱스 지정
int index = str.indexOf(String str, int fromIndex);
String text = "Hello, world!";
int index1 = text.indexOf('o'); // 4
int index2 = text.indexOf("world"); // 7
int index3 = text.indexOf("o", 5); // 8 (5번째 인덱스 이후에서 검색)
// -> 존재하지 않을 시 -1 반환
- ArrayList의 indexOf 메서드
int index = list.indexOf(Object o);
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
int index = list.indexOf("banana"); // 1
Share article