2016-12-24 53 views
-3
import java.util.*; 

public class Test2{ 
    public static void main(String[] args){ 
    String s1 = "Delivery"; 
    String s2 = s1.substring(8); 
    System.out.println(s2); 
    } 
} 

为什么这会给出一个空格?第八位不应该出界吗?java中的String.substring()

此外,为什么s1.charAt(8)会提示outOfBound错误?他们是否使用不同的方法来处理这个问题?

+1

不,可以在字符串末尾开始子字符串,它只是给你空字符串'“”'(字符串长度为0)。 –

+1

检查[Javadoc](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int))。 –

+3

该文档显示“抛出:IndexOutOfBoundsException” - 如果beginIndex为负数或大于此String对象的长度。“您可以采取这种方式来表示严格较大。 'beginIndex'允许等于length(在你的例子中都是8)。 –

回答

1

string.substring(int id)返回从索引id开始的字符串的子字符串。 id是一个索引,但不是位置!

请记住,索引从0开始计数! 请检查Javadoc

subString方法的部分看起来像这样:

int subLen = value.length - beginIndex; 
if (subLen < 0) { 
    throw new StringIndexOutOfBoundsException(subLen); 
} 
+1

那不,它不会返回一个字符,在这个例子中是不可能的。它返回一个字符串(在这个例子中是一个空字符串)。 –

3

substring方法抛出StringIndexOutOfBoundsException只有当beginIndex大于字符串length更大如图中下面的代码从String采取substring方法):

int subLen = value.length - beginIndex; 
if (subLen < 0) { 
    throw new StringIndexOutOfBoundsException(subLen); 
} 

此外,同样已经在Javadoc解释好,你可以看看here

返回一个新字符串,它是此字符串的一个子。子字符串 以指定索引处的字符开头,并扩展到该字符串的 结尾。实例:

“愁” .substring(2)返回 “快乐”

“哈比森” .substring(3)返回 “野牛”

“空虚” .substring(9)返回 “”(一个空字符串)

+0

谢谢!它有助于。 –

0

这将引发IndexOutOfBoundsException异常 - 如果beginIndex为负或大于您的字符串的长度。在你的情况beginIndex是8和字符串的长度也是8.这就是你没有得到IndexOutOfBoundsException的原因。

希望这会有所帮助!

0

建议您运行在一个IDE和调试 步进入方法串码和您的查询就会回答

检查子串方法的源代码

public String substring(int beginIndex) { 
     if (beginIndex < 0) { 
      throw new StringIndexOutOfBoundsException(beginIndex); 
     } 
     int subLen = value.length - beginIndex; 
     if (subLen < 0) { 
      throw new StringIndexOutOfBoundsException(subLen); 
     } 
     return (beginIndex == 0) ? this : new String(value, beginIndex, subLen); 
    } 

这里:

  1. 的开始索引为8,
  2. 8是不小于0
  3. subLen = 0和不小于0

尝试通过9到子,你会得到

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 
    at java.lang.String.substring(String.java:1875) 
    at com.iqp.standalone.Sample.main(Sample.java:14) 
0

请参阅Java文档中关于字符串在这里:Java Strings Doc

s1 lenght是7.

charAt方法看起来像这样:

public char charAt(int index) { 
    if ((index < 0) || (index >= value.length)) { 
     throw new StringIndexOutOfBoundsException(index); 
    } 
    return value[index]; 
} 

当然,它会给你错误!