简体   繁体   中英

Java: simpler way of cutting off end of string

Everytime I encounter this I ask myself the same question: Isn't there a simpler and less annoying way of cutting a string from the end by X characters.

Let's say I got "Helly there bla bla" and - why ever - I need to cut off the last 2 characters, resulting in "Helly there bla b" . I now would do the following:

String result = text.substring(0, text.length() - 2);

I rather want to do something like:

String result = text.cutOffEnd(2);

I know there are many String libraries out there, but don't know many of them and I never saw something like that so I hoped someone of you might know better :)

EDIT:

Q: Why don't you just build your own util method / class?

A: I don't want to use an own util method. I don't write a util method for "null or empty" or other trivial things. I go with the opinion that there MUST BE something available already as I would say that tons of people need this kind of function pretty often in their lifetime. Plus: I work in many different projects and just want to rely on a simple library call like "Strings.nullToEmpty(str)" etc. I just don't build something like that on my own, although it's trivial.

Q: why is text.substring(0, text.length() - 2); not good enough?

A: It's very bulky if you compare it with my desired function. Also, think of that: If you determine the string, it becomes even unhandier:

String result = otherClass.getComplicatedCalculatedText(par1, par2).substring(0,
otherClass.getComplicatedCalculatedText(par1, par2).length() - 2);

Obviously I'd need to use a local variable, which is so unnecessary at this point... As it could simply be:

String result = otherClass.getComplicatedCalculatedText(par1, par2).cutOffEnd(2);

By using some string library. I suggest Apache's commons lang.

For your case this is enough.

import org.apache.commons.lang.StringUtils;
String result = StringUtils.removeEnd( "Helly there bla bla", "la");

Go through the following code

public class OddNumberLoop {

  public static void main(String[] args) {

    String st1 = "Helly there bla bla";
    String st2 = st1.substring(0, st1.length() - 2);
    System.out.println(st2);

  }

}

Good Luck !!!

There is no built-in utility for this in the starnard library, but how hard is it to write a util method for this yourself?

public static String cutOffEnd(String s, int n) {
    return s == null || s.length() <= n ? "" : s.substring(0, s.length() - n);
}

A complete solution with checks included:

public static String cutOffEnd(String s, int n) {
    if (s == null)
        throw new NullPointerException("s cannot be null!");
    if (n > s.length())
        throw new IllegalArgumentException("n cannot be greater"
                      + " than the length of string!");

    return s.substring(0, s.length() - n);
}
  • By the way: Often such feature-requests are made to the java-compiler. Usually these features are not Compelling for the Language and won't be fixed .
  • Why do you like to cut it off? If its for a higher-level-solution then you like to match a pattern or structure. In this case you anyway shall use a own Util-Method for parsing.

A realistic Example:

String url = "http://www.foo.bar/#abc";
String site = url.substring(0, url.indexOf("#"));
// this shall be extracted into a utils-method 
// anyway like `MyURLParser.cutOfAnchor()`.

Its forbidden to ask for a concrete Library here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM