Java字符串操作实现:提取第三个空格后单词及索引12到末尾子串
实现思路
- 针对获取第三个空格后的单词需求:利用
indexOf的重载方法indexOf(String str, int fromIndex),依次从上次找到的空格位置的下一位开始查找,累计找到第三个空格后,再向后查下一个空格的位置,用substring方法截取两个位置中间的内容即可。如果第三个空格后没有后续空格,直接截取到字符串末尾。 - 针对获取索引12到末尾的内容需求:直接使用
String类的substring(int beginIndex)方法,传入参数12即可,该方法会自动返回从指定索引到字符串末尾的子串。
完整修改后代码
import java.util.Scanner; public class StringTest { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Please enter your string of words, sentences, or both!"); String entrypoint = in.nextLine(); System.out.println(entrypoint); int manippointone = entrypoint.length(); System.out.println("Your string is " + manippointone + " characters long."); int maniptwo = entrypoint.indexOf(" "); System.out.println("Found the first space in your string at character number: " + (maniptwo + 1)); // 新增功能1:获取第三个空格之后的单词 int firstSpace = entrypoint.indexOf(" "); int secondSpace = entrypoint.indexOf(" ", firstSpace + 1); int thirdSpace = entrypoint.indexOf(" ", secondSpace + 1); int nextSpaceAfterThird = entrypoint.indexOf(" ", thirdSpace + 1); String wordAfterThirdSpace; if (nextSpaceAfterThird == -1) { wordAfterThirdSpace = entrypoint.substring(thirdSpace + 1); } else { wordAfterThirdSpace = entrypoint.substring(thirdSpace + 1, nextSpaceAfterThird); } System.out.println("第三个空格之后的单词是:" + wordAfterThirdSpace); // 新增功能2:获取索引12到末尾的内容 String contentFromIndex12 = entrypoint.substring(12); System.out.println("索引12到末尾的内容是:" + contentFromIndex12); in.close(); } }
注意事项
上述实现默认输入字符串满足作业测试条件(至少包含3个空格、总长度大于等于13),没有额外加异常处理逻辑。如果需要兼容边界情况,可以提前做判断:
- 每次查找空格时如果返回值为-1,说明空格数量不足,可输出对应提示
- 截取索引12之前先判断
entrypoint.length() > 12,不满足条件时输出提示即可
内容的提问来源于stack exchange,提问作者hello_world
相关产品推荐
相关产品推荐

