Java 是否有子字符串(开始,长度)函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19223166/
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-08-12 15:12:09  来源:igfitidea点击:

Is there a substring(start, length) function?

javastringsubstring

提问by James Meade

I am trying to use a similar method to C#'s string.SubString(int start, int length).

我正在尝试使用与 C# 类似的方法string.SubString(int start, int length)

But the substring function in Java is string.substring(int start, int end).

但是 Java 中的 substring 函数是string.substring(int start, int end).

I want to be able to pass a start position and a length to the substring function.

我希望能够将起始位置和长度传递给 substring 函数。

Can anyone help me to solve this issue?

谁能帮我解决这个问题?

采纳答案by Danstahr

It could be something like

它可能是这样的

String mySubString(String myString, int start, int length) {
    return myString.substring(start, Math.min(start + length, myString.length()));
}

     

     

回答by tagtraeumer

yes

是的

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int, int)

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int, int)

public String substring(int beginIndex, int endIndex)

公共字符串子字符串(int beginIndex,int endIndex)

you just need to calculate a little in order to get the endIndex.

您只需要稍微计算一下即可获得 endIndex。

回答by Anirudha

The closest you can get is by using the String's constructor

最接近的是使用 String 的构造函数

new String(input.getBytes(),start,length);