Java substring 遇到的坑

旧城等待, 2021-12-10 06:23 367阅读 0赞

如下:定义一个string【长度为6,那么下标就应该是0到5】:

  1. String s = "123456";
  2. 我们如何取出整个s呢?

当初我的想法是s.substring(0,5);======>>>>试验一下

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwOTY5MTA4_size_16_color_FFFFFF_t_70

这时有点懵,点击去查看源码发现确实是理解错误了,他并不包含最后一个【根据源码的例子可以看出】

sbustring源码:

  1. /**
  2. * Returns a new string that is a substring of this string. The
  3. * substring begins at the specified <code>beginIndex</code> and
  4. * extends to the character at index <code>endIndex - 1</code>.
  5. * Thus the length of the substring is <code>endIndex-beginIndex</code>.
  6. * <p>
  7. * Examples:
  8. * <blockquote><pre>
  9. * "hamburger".substring(4, 8) returns "urge"
  10. * "smiles".substring(1, 5) returns "mile"
  11. * </pre></blockquote>
  12. *
  13. * @param beginIndex the beginning index, inclusive.
  14. * @param endIndex the ending index, exclusive.
  15. * @return the specified substring.
  16. * @exception IndexOutOfBoundsException if the
  17. * <code>beginIndex</code> is negative, or
  18. * <code>endIndex</code> is larger than the length of
  19. * this <code>String</code> object, or
  20. * <code>beginIndex</code> is larger than
  21. * <code>endIndex</code>.
  22. */
  23. public String substring(int beginIndex, int endIndex) {
  24. if (beginIndex < 0) {
  25. throw new StringIndexOutOfBoundsException(beginIndex);
  26. }
  27. if (endIndex > value.length) {
  28. throw new StringIndexOutOfBoundsException(endIndex);
  29. }
  30. int subLen = endIndex - beginIndex;
  31. if (subLen < 0) {
  32. throw new StringIndexOutOfBoundsException(subLen);
  33. }
  34. return ((beginIndex == 0) && (endIndex == value.length)) ? this
  35. : new String(value, beginIndex, subLen);
  36. }

发表评论

表情:
评论列表 (有 0 条评论,367人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Linux遇到

    最近换了一个电脑  新安装了一个linux   装在虚拟机下   具体的安装过程则合理不在赘述 讲讲安装之后发现的问题吧  首先是没有汉字  重新下载安装  这个不复杂

    相关 Xposed遇到

    如果某个APP的dex有多个在安卓5,0以上ART会合成一个oat文件。那么5.0以下会存在多个dex。 所以在5.0以下hook一个某个方法,而这个方法不在主dex,而存

    相关 Hibernate 遇到

    传统的java开发中,通常分领域模型,model。在对数据进行保存的时候通常一般会保存到vo中,显示数据到页面的时候通常是dto,前几天遇到个坑,在dto中封装实体对象,...