获取子字符串

通过String类的substring()方法可对字符串进行截取。这些方法的共同点就是都是利用字符串的下标进行截取。应明确字符串下标是从0开始的。

substring()方法被两种不同的方法重载,来满足不同的需要。

1substring(int beginIndex)

该方法返回的是从指定的索引位置开始截取直到该字符串的结尾的子串。

语法:

str.substring(int beginIndex)

beginIndex:指定从某一索引处开始截取字符串。

  截取字符串,实例代码如下:

String str = "Hello Word";                 //定义字符串str

String substr = str.substring(3);         //获取字串,此时substr值为lo Word

使用substring(beginIndex)截取字串的过程如图1所示。

 

         1  substring(3)的截取过程

 注意在字符串中空格占用一个索引位置。

2substring(int beginIndex , int endIndex)

该方法返回的是从字符串某一索引位置开始截取至某一索引位置结束的子串。

语法:

substring(int beginIndex, int endIndex)

beginIndex:开始截取子字符串的索引位置。

endIndex:子字符串在整个字符串中的结束位置。

  在项目中创建类Subs,在主方法中创建String对象,实现使用substring()方法对字符串进行截取,并将截取后形成的新串输出。

public class Subs {                                                 //创建类

                  public static void main(String args[]) {   //主方法

                        String str = "hello word";                 //定义的字符串

                        String substr = str.substring(0,3);     //对字符串进行截取

                        System.out.println(substr);               //输出截取后的字符串

                  }

}

运行结果如图2所示:

 

        2  运行结果