Java:切断字符串末尾的更简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26215365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:30:49  来源:igfitidea点击:

Java: simpler way of cutting off end of string

javasubstring

提问by BAERUS

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.

每次我遇到这个问题时,我都会问自己同样的问题:是否有一种更简单且不那么烦人的方法可以将字符串从末尾剪下 X 个字符。

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:

假设我得到了"Helly there bla bla"- 为什么 - 我需要切断最后 2 个字符,导致"Helly there bla b". 我现在会做以下事情:

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 :)

我知道那里有很多 String 库,但不知道其中很多,而且我从未见过类似的东西,所以我希望你们中的某个人可能更了解 :)

EDIT:

编辑:

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

问:为什么不构建自己的 util 方法/类?

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.

A:我不想使用自己的 util 方法。我不会为“空或空”或其他琐碎的事情编写 util 方法。我认为必须已经有一些可用的东西,因为我会说很多人在他们的一生中经常需要这种功能。另外:我在许多不同的项目中工作,只是想依赖一个简单的库调用,比如“Strings.nullToEmpty(str)”等。我只是不会自己构建类似的东西,尽管它很简单。

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

问:为什么text.substring(0, text.length() - 2);不够好?

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:

A:和我想要的功能比起来就很笨重了。另外,请想一想:如果您确定字符串,它会变得更加不方便:

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 Rustam

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

通过使用一些字符串库。我建议使用 Apache 的公共语言。

For your case this is enough.

对于你的情况,这就足够了。

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

回答by Dhanushka Gayashan

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 !!!

祝你好运 !!!

回答by icza

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?

starnard 库中没有为此提供内置实用程序,但是自己为此编写一个 util 方法有多难?

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 Grim

  • 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-Methodfor parsing.
  • 顺便说一句:通常此类功能请求是向 java 编译器发出的。通常这些功能对于语言来说并不引人注目,也不会被修复
  • 你为什么喜欢剪掉它?如果它用于更高级别的解决方案,那么您喜欢匹配模式或结构。在这种情况下,您无论如何都应使用自己的 Util-Method进行解析。

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.

禁止在这里索取具体的图书馆。