Java的字符串截取函数和js是一样的,不仅大小写是一样的,而且定义也是一样,都是截取开始位置到结束位置的字符串,用法完全一样,不过java没有提供js的substr函数了,想截取只能使用这个substring了,和上文描述的方法就不一样了,好在也容易理解,先看一下源码:
/**
* Returns a new string that is a substring of this string. The
* substring begins at the specified <code>beginIndex</code> and
* extends to the character at index <code>endIndex - 1</code>.
* Thus the length of the substring is <code>endIndex-beginIndex</code>.
* <p>
* Examples:
* <blockquote><pre>
* "hamburger".substring(4, 8) returns "urge"
* "smiles".substring(1, 5) returns "mile"
* </pre></blockquote>
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified substring.
* @exception IndexOutOfBoundsException if the
* <code>beginIndex</code> is negative, or
* <code>endIndex</code> is larger than the length of
* this <code>String</code> object, or
* <code>beginIndex</code> is larger than
* <code>endIndex</code>.
*/
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
看函数的描述,截取的字段是
开始位置和结束位置 - 1的字符串。
继续实现上文的例子:
public static void testsubstring(){
String ls_1 = "01中3456789";
// 取左面3位
String lString = ls_1.substring(0,3);
System.out.println(lString);
// 去除左面的3位
lString = ls_1.substring(3);
System.out.println(lString);
// 取右面3位
lString = ls_1.substring(ls_1.length()-3,ls_1.length());
System.out.println(lString);
// 去除右面3位
lString = ls_1.substring(0,ls_1.length()-3);
System.out.println(lString);
}
输出:
01中
3456789
789
01中3456
开发语言很多,没有规范,所以一定要细心,不能经验主义。现在只学习一门语言是不可能的,都记住也是不可能的,所以会查帮助,能用就可以了。