프로그래밍언어/Java

자바(Java) 문자열(String) 대문사, 소문자 변환하기

멍토 2022. 2. 9.

 

가끔 문자열을 대문자로 바꾸거나 소문자로 바꿔야 하는 일이 생긴다.

이럴 때 String 클래스의 내장 기능을 사용하면 편하게 바꿀 수 있다.

아스키코드로 바꿀 수도 있지만 이미 만들어진 기능을 쓰는 게 더 좋지 않은가?

이번 포스팅에서는 대문자를 소문자로 바꾸거나 소문자를 대문자로 바꾸는 방법에 대해서 알아보자.

 

대문자로 바꾸기

 

자바의 공식문서를 보면 toUpperCase라는 메서드가 있으며 해당 메서드가 대문자로 바꿔주는 메서드이다.

알파벳이 아닌 문자는 영향을 받지 않는다.

정확히는 String의 경우 불변 객체이기 때문에 해당 객체가 바뀌는 것이 아니라 대문자로 이루어진 객체를 반환해준다.

 

@Test
@DisplayName("소문자를 대문자로 변환한다.")
void upper() {
    // given
    String expected = "ABCDEF!!";
    String text = "abcdef!!";

    // when
    String answer = text.toUpperCase();

    // then
    assertThat(answer).isEqualTo(expected);
}

 

 

소문자로 바꾸기

 

 

자바의 공식문서를 보면 toLowerCase라는 메서드가 있으며 해당 메서드가 소문자로 바꿔주는 메서드이다.

대문자 변환과 마찬가지로 알파벳이 아닌 문자는 영향을 받지 않는다.

 

@Test
@DisplayName("대문자를 소문자로 변환한다.")
void lower() {
    // given
    String expected = "abcdef!!";
    String text = "ABCDEF!!";

    // when
    String answer = text.toLowerCase();

    // then
    assertThat(answer).isEqualTo(expected);
}

 

 

공부해보기

따로 공부가 하고 싶은 사람들은 아래 깃허브에서 코드를 받아서 연습을 하면 된다.

자바공부용 깃허브 : https://github.com/daum7766/java-study

 

GitHub - daum7766/java-study: test 코드를 기반으로 자바의 기능을 학습한다.

test 코드를 기반으로 자바의 기능을 학습한다. Contribute to daum7766/java-study development by creating an account on GitHub.

github.com

 

 

참고자료

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html

 

String (Java SE 11 & JDK 11 )

Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argum

docs.oracle.com

 

댓글

💲 광고입니다.