Java如何获取字符串的一部分或子字符串?
以下代码段演示了如何从字符串中获取某些部分。为此,我们使用该String.substring()方法。第substring()一种方法采用单个参数,beginIndex即子字符串开始处的索引。此方法将从字符串的开始索引到字符串的结尾返回一部分字符串。
第二种方法,substring(intbeginIndex,intendIndex)采用子字符串操作的开始索引和结束索引。该substring()方法的索引是从零开始的索引,这意味着字符串中的第一个字符从index开始0。
package org.nhooo.example.lang; public class SubstringExample { public static void main(String[] args) { //该程序演示了如何获取字符串的一部分 //或我们所谓的子字符串。JavaString类提供 //带有一些重载参数的子字符串方法。 String sentence = "The quick brown fox jumps over the lazy dog"; //具有单个参数beginIndex的第一个子字符串方法 //将从开始索引处获取字符串的一部分 //直到字符串中的最后一个字符。 String part = sentence.substring(4); System.out.println("Part of sentence: " + part); //第二个子字符串方法采用两个参数beginIndex //和endIndex。此方法返回从开始的子字符串 //从beginIndex到endIndex。 part = sentence.substring(16, 30); System.out.println("Part of sentence: " + part); } }
此代码段打印出以下结果:
Part of sentence: quick brown fox jumps over the lazy dog Part of sentence: fox jumps over