关于Java代码中,length(),trim(),substring()方法
length()用于获取字符串的长度
package example0521;
public class Demo6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "asdfghjkl";
System.out.println("该字符串的长度是:" + a.length());
}
}
输出:
trim()方法用于去除字符串两边的空格,在这里我们可以结合length()方法进行判断
package example0521;
public class Demo6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = " asdfghjkl ";
System.out.println("该字符串去掉空格之前的长度是:" + a.length());
System.out.println("该字符串去掉空格的长度是:" + a.trim().length());
}
}
输出:
substring(beginIndex,endIndex)方法里面有两个方法用于你需要截取字符串的起始和终止位置。这是个闭开,注意JAVA中不管是数组还是字符串下标都是从0开始,比如字符串"asd",你需要获取a,那么a的下标就是0
package example0521;
public class Demo6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "asdfghjkl";
System.out.println(a.substring(0,2));
}
}
输出
我们选取了(0.2)这个区间,但并不包含下标2所对应的d