Dev Hyeri

기술스택/Java, Spring

[Java, Spring] 메소드_문자열

_hyeri 2024. 6. 4. 23:15

charAt() 

public char charAt(int index)

The charAt() method returns the character at the specified index in a string(The index of the first character is 0)

Return : 지정된 인덱스의 문자를 char 타입으로 반환

Throws: IndexOutOfBoundsException

 

특이사항 : 

 

  • charAt 메서드는 지정된 인덱스의 문자를 char 타입으로 반환합니다.
  • char 타입은 내부적으로 정수로 처리되며, 각 문자는 고유한 ASCII 값을 가집니다.
  • 문자를 결합할 때 ASCII 값이 더해지는 것을 피하려면 문자열 결합을 사용해야 합니다.

예제

 

public class Main {
    public static void main(String[] args) {
        String word = "AB";
        
        // 첫 번째 문자와 마지막 문자를 가져옴
        char firstChar = word.charAt(0); // 'A'
        char lastChar = word.charAt(1);  // 'B'
        
	System.out.println(firstChar + lastChar);  // 출력:  131

        // ★ ""를 사용하여 문자를 문자열로 결합
        
        System.out.println(firstChar); // 출력:  A
        System.out.println(lastChar);  // 출력:  B
	System.out.println("" + firstChar + lastChar);  // 출력:  AB

        
        String result = "" + firstChar + lastChar;
        System.out.println(result); // 출력 : AB
    }
}

 

 

 

 

matches()

public boolean matches(String regex)

 

The matches() method searches a string for a match against a regular expression, and returns the matches.

전체 문자열이 정규표현식과 일치하는지 검사한다. 간단하게 문자열의 형식을 검사할 수 있다. 

매개변수 : 정규표현식 

Return : 참이면 True 거짓이면 False

Throws: IndexOutOfBoundsException

 

예제

public class Main{

	public static void main(String[] args){
    	String str1 = "HelloWorld";
        String str2 = "Hello World";
        
        // 알파벳 대문자와 소문자로만 이루어진 문자열
        String regex  = "[A-Za-z]+";
        
        System.out.println(str1.matches(regex)); // true
        System.out.println(str2.matches(regex)); // false : 공백을 포함함
       
    }
}

 

활용 

이메일 형식 검사

public class Main{

	public static void main(String[] args){
    	String email = "email@example.com"
        
        // 이메일 형식
        String regex  = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}$";
        
        System.out.println(email.matches(regex)); // true
        
    }
}
이메일 형식 정규표현식 설명 
^ : 문자열의 시작 
[A-Za-z0-9._%+-]+ : 알파벳 대소문자, 숫자, 점, 언더바,퍼센트,더하기,빼기 중 하나 이상의 문자
@ : @ 문자
\\. : 점 문자
[A-Z|a-z]{2,} : 알파벳 대소문자 중 두 개 이상의 문자
$ : 문자열의 끝

'기술스택 > Java, Spring' 카테고리의 다른 글

[Java, Spring] 입력 클래스  (0) 2024.06.04