怎样才能select得到原字符串代表的除首字母两个字符以外的子串呢?
How can I select the substring represented by the original string except the two initial characters?
我知道在 Java 中我可以从 String 对象中提取一个子字符串,执行如下操作:
String string= "Hello World";
String subString = string.substring(5);
并且在这个 wat subString 变量将只包含 Hello 字符串
而且我知道我还可以为 select 子字符串指定 2 个索引,例如:
String subString = string.substring(6, 11);
这将 select World 字符串。
但是,如果给定一个字符串,我想要 select 原始字符串表示的除两个初始字符之外的子字符串,我该怎么办?
例如我有:
String value = "12345"
我的子字符串必须是 345
我该怎么做?
String subString = string.substring(5);
并不像你想的那样。
实际上string.substring(2)
returns一个String,包含第一个String中除前两个字符外的所有字符。
当您想要一个从输入字符串开头开始的子字符串时,您可以使用两个参数版本 - 例如前 5 个字符的 string.substring(0,5)
。
来自Java docs,
Returns a new string that is a substring of this string. The substring
begins with the character at the specified index and extends to the
end of this string.
Examples:
"unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" (an empty string)
Parameters: beginIndex the beginning index, inclusive. Returns: the
specified substring. Throws: IndexOutOfBoundsException - if beginIndex
is negative or larger than the length of this String object.
public static void main(String[] args) {
String sb = "12345";
String s = sb.substring(2);
System.out.println(s);
}
输出
345
我知道在 Java 中我可以从 String 对象中提取一个子字符串,执行如下操作:
String string= "Hello World";
String subString = string.substring(5);
并且在这个 wat subString 变量将只包含 Hello 字符串
而且我知道我还可以为 select 子字符串指定 2 个索引,例如:
String subString = string.substring(6, 11);
这将 select World 字符串。
但是,如果给定一个字符串,我想要 select 原始字符串表示的除两个初始字符之外的子字符串,我该怎么办?
例如我有:
String value = "12345"
我的子字符串必须是 345
我该怎么做?
String subString = string.substring(5);
并不像你想的那样。
实际上string.substring(2)
returns一个String,包含第一个String中除前两个字符外的所有字符。
当您想要一个从输入字符串开头开始的子字符串时,您可以使用两个参数版本 - 例如前 5 个字符的 string.substring(0,5)
。
来自Java docs,
Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
Examples:
"unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" (an empty string)
Parameters: beginIndex the beginning index, inclusive. Returns: the specified substring. Throws: IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
public static void main(String[] args) {
String sb = "12345";
String s = sb.substring(2);
System.out.println(s);
}
输出
345