본문 바로가기
Java

[java] 특정 문자열에 문자 존재 여부 확인 함수

by 간장공장공차장 2024. 11. 30.
반응형

1. String.contains()

  • 문자열에 특정 문자열(또는 문자)이 포함되어 있는지 확인합니다.
  • 반환값: boolean (true/false)
String str = "Hello, World!"; 
boolean result = str.contains("World"); 
System.out.println(result); // true

2. String.indexOf()

  • 특정 문자나 문자열이 처음 등장하는 위치를 반환합니다.
  • 값이 -1이면 존재하지 않는다는 뜻입니다.
  • 반환값: int (위치 또는 -1)
String str = "Hello, World!"; 
int index = str.indexOf('W'); 
System.out.println(index); // 7 (존재하지 않으면 -1 반환)

5. String.charAt() (사용자 정의 조건으로)

  • 문자열에서 특정 위치의 문자를 가져와 직접 비교합니다.
  • 반환값: char (위치에 따른 문자)
String str = "Hello, World!"; 
for (int i \= 0; i < str.length(); i++) {
	if (str.charAt(i) == 'W') { 
    	System.out.println("Character found at index " + i); 
        break; 
        }
    }
반응형