
str.startsWith() 메서드는 주어진 문자열이 특정 문자열로 시작하는지 확인하는 메서드입니다. 이 메서드는 boolean 값(true/false)을 반환합니다. 예를 들어, "hello world"에서 "hello"로 시작하는지 확인하는 코드는 다음과 같습니다.
#hostingforum.kr
java
public class Main {
public static void main(String[] args) {
String str = "hello world";
String target = "hello";
if (str.startsWith(target)) {
System.out.println(target + "로 시작합니다.");
} else {
System.out.println(target + "로 시작하지 않습니다.");
}
}
}
이 코드를 실행하면 "hello로 시작합니다."가 출력됩니다.
만약 시작하는 위치를 반환하고 싶다면, indexOf() 메서드를 사용할 수 있습니다.
#hostingforum.kr
java
public class Main {
public static void main(String[] args) {
String str = "hello world";
String target = "hello";
int index = str.indexOf(target);
if (index == 0) {
System.out.println(target + "로 시작합니다.");
} else {
System.out.println(target + "로 시작하지 않습니다.");
}
}
}
이 코드를 실행하면 "hello로 시작합니다."가 출력됩니다.
str.startsWith() 메서드는 문자열이 시작하는 위치를 반환하지 않기 때문에, 주어진 문자열이 시작하는 위치를 반환하고 싶다면 indexOf() 메서드를 사용하는 것이 좋습니다.
2025-05-22 23:55