public boolean startsWith(String prefix)
매개변수(파라미터) : prefix(접두사) 문자열의 시작 부분과 비교할 문자열
리턴값
boolean true -> 호출한 문자열이 주어진 prefix와 일치하면
boolean false -> 호출한 문자열이 주어진 prefix와 일치하지 않으면
예를 들어보자.
public class Main {
public static void main(String[] args) {
String text = "삭제?id=1";
System.out.println(text.startsWith("삭제")); // true
System.out.println(text.startsWith("등록")); // false
System.out.println(text.startsWith("삭제?id")); // true }
}
}
String 타입의 변수 text에 “삭제?id=1”을 담았다.
text.startsWith(“삭제”) ->
.strartsWith(“삭제”)를 통해 text에 있는 값이 “삭제”로 시작되는지 판단한다. -> 맞다 -> true 값 반환
text.startsWith("등록") ->
.strartsWith(“등록”)를 통해 text에 있는 값이 “등록”으로 시작되는지 판단한다. -> 아니다 -> false 값 반환
text.startsWith("삭제?id") ->
.strartsWith(“삭제?id”)를 통해 text에 있는 값이 “삭제?id”로 시작되는지 판단한다. -> 맞다 -> true 값 반환
좀 더 긴 예를 들어보자
public class CommandChecker {
public static void main(String[] args) {
String command = "삭제?id=5";
if (command.startsWith("삭제")) {
System.out.println("삭제 명령 실행!");
} else if (command.startsWith("등록")) {
System.out.println("등록 명령 실행!");
} else {
System.out.println("알 수 없는 명령입니다.");
}
}
}
command.startsWith(“삭제”) 이므로 command의 값이 “삭제~~”로 시작하면 true 값을 반환됨을 알 수 있다.
startsWith() 메서드는 시작 위치를 지정할 수 있는 또 다른 오버로딩된 버전도 제공한다.
public Boolean startsWith(String prefix, int offset)
파라미터 : prefix(접두사) 비교할 접두사.
offset : 문자열에 몇 번째 위치부터 비교를 시작할지 지정.
public class Main {
public static void main(String[] args) {
String text = "삭제?id=5";
System.out.println(text.startsWith("삭제", 0)); // true
System.out.println(text.startsWith("id", 3)); // true
System.out.println(text.startsWith("삭제", 1)); // false
}
}
startsWith() 메서드는 문자열의 시작 부분에서 주어진 prefix의 길이 만큼 문자를 하나씩 비교한다.
단,
** 주의.
prefix가 null값이면 nullPointerException 컴파일 오류가 발생한다.
startsWith() 메서드를 사용할때 prefix 값이 null 값인지 확인하자.