특정 문자열에서 원하는 문자가 포함되어 있는지 확인해야하는 소스를 넣을때가 종종 있습니다.
문자열을 찾는 방법
사용법 설명
| 함수 | 설명 |
|---|---|
| indexOf(String str) | 대상문자열에 인자값으로 주어지는 String값이 있는지 검색합니다. |
| indexOf(char ch) | 대상문자열에 인자값으로 주어지는 char값이 있는지 검색합니다. |
| indexOf(String str, int fromIndex) | 대상문자열에 첫번째 인자값으로 주어지는 String값이 있는지 두번째 인자값의 index부터 검색합니다. |
| indexOf(char ch, int fromIndex) | 대상문자열에 첫번째 인자값으로 주어지는 char값이 있는지 두번째 인자값의 index부터 검색합니다. |
public class indexOf {
public static void main(String[] args) {
String s = "Hello welcome to the this place";
System.out.println(s.indexOf("welcome")); //문자열 검색
System.out.println(s.indexOf("t")); //단어 검색
System.out.println(s.indexOf("welcome",10)); //문자열을 10번째 index부터 검색
System.out.println(s.indexOf("t",10)); //단어를 10번째 index부터 검색
if(s.indexOf("welcome")!=-1) {
System.out.println("문자가 포함되어 있습니다.");
}else {
System.out.println("문자가 포함되어 있지 않습니다.");
}
}
}
만약 뒤에서부터 index값을 검색하고 싶으면 lastIndexOf()메소드를 사용하면 되고 사용법은 indexOf()와 같습니다.
| 함수 | 설명 |
|---|---|
| indexOf(int ch) | 유니코드표의 값을 사용하여 원하는 문자열의 위치를 뒤에서부터 찾습니다 |
| indexOf(String str) | 문자열에서 같은 문자의 위치를 뒤에서부터 찾습니다 |
| indexOf(int ch, int fromIndex) | 유니코드표의 값을 사용하여 원하는 문자열을 찾지만 마지막에서부터 찾는 것이 아닌 fromIndx의 값에서 시작해서 문자열을 찾아줍니다 |
| indexOf(String str, int fromIndex) | 문자열에서 같은 문자의 위치를 찾지만 뒤에서부터 fromIndex의 값에서 시작해서 문자열을 찾아줍니다 |
문자열 검색만을 위한다면 contains를 활용하는것이 가장 효율적입니다. contains메소드는 문자열에 검색하고자 하는 문자가 있는지 확인하여 포함되어있다면 true를 포함되어있지 않다면 false값을 리턴합니다.
영문자나 숫자등의 정규표현식이 대상 문자열에 포함되어 있는지 아닌지 확인해야 할때 유용합니다.
사용 방법
public class contains {
public static void main(String[] args) {
String s = "Hello welcome to the this place";
if(s.contains("welcome")) {
System.out.println("문자가 포함되어 있습니다.");
}else {
System.out.println("문자가 포함되어 있지 않습니다.");
}
}
}
public class matches {
public static void main(String[] args) {
String s = "Hello welcome to the this place";
//특정 문자열 검색
if(s.matches(".*welcome.*")) {
System.out.println("문자가 포함되어 있습니다.");
}else {
System.out.println("문자가 포함되어 있지 않습니다.");
}
//영문자가 있는지 검색
if(s.matches(".*[a-zA-Z].*")) {
System.out.println("영문자가 포함되어 있습니다.");
}else {
System.out.println("영문자가 포함되어 있지 않습니다.");
}
//숫자가 있는지 검색
if(s.matches(".*[0-9].*")) {
System.out.println("숫자가 포함되어 있습니다.");
}else {
System.out.println("숫자가 포함되어 있지 않습니다.");
}
}
}