67

How can I trim the leading or trailing characters from a string in java?

For example, the slash character "/" - I'm not interested in spaces, and am looking to trim either leading or trailing characters at different times.

Jasperan
  • 2,154
  • 1
  • 16
  • 40
Brad Parks
  • 66,836
  • 64
  • 257
  • 336

6 Answers6

107

You could use

Leading:

System.out.println("//test/me".replaceAll("^/+", ""));

Trailing:

System.out.println("//test/me//".replaceAll("/+$", ""));
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • 5
    that seems to work good... you can [test it online here](http://ideone.com/shHHV9) – Brad Parks Sep 05 '14 at 18:22
  • 1
    @SayanSil the solution is using regex syntax. ^/+ selects a slash only at the beginning of the string. – hayfreed Apr 23 '18 at 20:26
  • 1
    The first one could be replaced with `System.out.println("//test/me".replaceFirst("^/+", ""));` It's likely more efficient as it won't try to find any further matches. – John Gilmer Oct 30 '22 at 20:08
44

You can use Apache StringUtils.stripStart to trim leading characters, or StringUtils.stripEnd to trim trailing characters.

For example:

System.out.println(StringUtils.stripStart("//test/me", "/"));

will output:

test/me

Note that if for some reason you can't use the whole StringUtils library, you could just rip out the relevant parts, as detailed here:

Community
  • 1
  • 1
Brad Parks
  • 66,836
  • 64
  • 257
  • 336
6

Trim with Character, String, or Regex

If run-time is not a big issue for you, then this code will prove really helpful.

public class StringTrimmer {
    public static String trim(String string, char ch){
        return trim(string, ch, ch);
    }

    public static String trim(String string, char leadingChar, char trailingChar){
        return string.replaceAll("^["+leadingChar+"]+|["+trailingChar+"]+$", "");
    }

    public static String trim(String string, String regex){
        return trim(string, regex, regex);
    }

    public static String trim(String string, String leadingRegex, String trailingRegex){
        return string.replaceAll("^("+leadingRegex+")+|("+trailingRegex+")+$", "");
    }

    // test
    public static void main(String[] args) {
        System.out.println(trim("110100", '1', '0')); // outputs: 01
        System.out.println(trim("**Aa0*#**", '*')); // outputs: Aa0*#
        System.out.println(trim("123##22222", "12", "22")); // outputs: 3##2
        System.out.println(trim("101101##10101", "101")); // outputs: ##10
        System.out.println(trim("123##abcde", "\\d", "[c-e]")); // outputs: ##ab
    }
}
Minhas Kamal
  • 20,752
  • 7
  • 62
  • 64
5

You could use a simple iteration if you want to remove the leading characters from a string :

String removeLeadingChar(String s, char c) {
    int i;
    for(i = 0; i < s.length() && s.charAt(i) == c; ++i);
    return s.substring(i);
}

same logic applies if you want to remove any trailing char.

Oleg
  • 1,479
  • 3
  • 21
  • 42
5

For those using Spring:

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/StringUtils.html#trimTrailingCharacter-java.lang.String-char-

import org.springframework.util.StringUtils;    

public void setFileName(String fileName) {
    // If the extension does not exist trim the trailing period
    this.fileName = StringUtils.trimTrailingCharacter(fileName,'.');
}
Gabe Gates
  • 902
  • 1
  • 14
  • 19
1

My version of trimming leading and/or trailing String s from String str. Both arguments may be null. When str does not has leading and/or trailing s, it is not changed.

String trim(String str, String s) {
    String res = s == null ? str : str == null ? null : s.length() >= str.length() ? str : str.replaceFirst(s, "");
    if ((res != null) && (s != null) && (res.length() >= s.length())) {
        return res.substring(res.length() - s.length(), res.length()).equals(s) ? res.substring(0, res.length() - s.length()) : res;
    }
    return res;
}
Andrushenko Alexander
  • 1,839
  • 19
  • 14