본문 바로가기
Baeldung번역&공부/Java-string

문자열에서 마지막 문자를 지우는법(How to Remove the Last Character of a String?)

by ms727 2025. 2. 1.

원본 글: https://www.baeldung.com/java-remove-last-character-of-string

 

How to Remove the Last Character of a String? | Baeldung

Learn how to remove the last character of a String with core Java or using external libraries.

www.baeldung.com

 

문자열에서 마지막 문자를 지우는 방법들을 소개합니다.

 

1. Using String.substring()

제일 간단한 방법은 subString() 메서드를 사용하는 것입니다.

파라미터로 시작 인덱스인 0와 문자열 길이-1값을 넣어서 제거하는 것입니다.  문자열 길이 -1은 length() 메서드를 통하여 간단하게 구할 수 있습니다.

그러나 이 방식의 문제점은 null-safe 하지 않습니다. 만약 빈 문자열이 들어오면 에러를 발생시킵니다.

그렇기에 null 검증을 추가로 넣어줘서 해결해야합니다.

 

@Test
public void substring_test() {
    String result = "test";
    String expected = "tes";

    result = removeLastChar(result);
    Assertions.assertEquals(result, expected);
}

public static String removeLastChar(String s) {
    return (s == null || s.length() == 0)
            ? null
            : (s.substring(0, s.length() - 1));
}

 

Java8이상이라면 이렇게도 구성할 수 있습니다.

 

@Test
public void substring_test_java8_above() {
    String result = "test";
    String expected = "tes";

    result = removeLastCharJava8Above(result);
    Assertions.assertEquals(result, expected);
}
public static String removeLastCharJava8Above(String s) {
    return Optional.ofNullable(s)
            .filter(str -> str.length() != 0)
            .map(str -> str.substring(0,str.length()-1))
            .orElse(s);
}

 

2. Using StringUtils.subString()

Apache Common라이브러리에 있는 유틸함수를 이용해 마지막 문자를 제거할 수 있습니다.

이 라이브러리의 특징이 그렇듯, null-safe하게 동작합니다.

 

@Test
public void apache_common_substring_test() {
    String result = "test";
    String expected = "tes";

    result = StringUtils.substring(result, 0, result.length()-1);
    Assertions.assertEquals(result, expected);
}

3. Using StringUtils.chop()

StringUtils에 있는 chop()이라는 메서드를 통해서 마지막 문자열을 제거할 수 있습니다.

null-safe하고 정말 간단하게 작동합니다.

@Test
public void chop_test() {
    String result = "test";
    String expected = "tes";
    Assertions.assertEquals(StringUtils.chop(result), expected);
}

해당 메서드는 그냥 간단하게 마지막 문자를 지워줍니다.

4. Using Regular Expression

 

정규표현식을 통해서 마지막 문자를 지울 수 있습니다.

replaceAll() 함수에 정규표현식을 넣어서 마지막 문자를 빈문자로 치환할 수 있습니다.

 

@Test
public void regular_expression_test() {
    String result = "test";
    String expected = "tes";
    Assertions.assertEquals(result.replaceAll(".$", ""), expected);
}

 

다만, 이 방식은 null-safe하지 않아서 추가로 null에 대한 검증을 수행해줘야합니다.

(s == null) ? null : s.replaceAll(".$", "");

 

마지막으로 Java8이상 버전에서 사용할 수 있는 방법입니다.

 

@Test
public void regular_expression_test_java8_above() {
    String result = "test";
    String expected = "tes";

    result = removeLastCharRegexJava8Above(result);
    Assertions.assertEquals(result, expected);
}

public static String removeLastCharRegexJava8Above(String s) {
    return Optional.ofNullable(s)
            .filter(str -> str.length() != 0)
            .map(str -> str.replaceAll(".$",""))
            .orElse(s);
}

5. 결론

 

이 글에서는 마지막 문자를 지우는 여러 방법에 대해서 확인하였습니다.

많은 유연성이 필요하고 많은 문자를 제거해야하는 경우 정규표현식을 사용한 방법을 권하고 있습니다.

 

저라면은 요구사항이 마지막 문자만 지우는것이라면 chop()메서드를 활용할 것 같습니다.