You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java使用subString方法实现无限制空格拆分字符串求助

用subString实现无限制拆分句子单词(Java)

问题分析

你当前的代码存在两个核心问题:

  • 使用了老师禁止的split方法
  • 手动指定打印数组前两个元素,无法适配任意数量的单词

下面用最基础的循环+subString实现需求,完全不用高级方法:

实现代码

package NF2;

import java.util.Scanner;

public class Exercici13 {
    public static void main(String[] args) {
        Scanner ent = new Scanner(System.in);
        String sentence;

        System.out.println("Enter a non-empty text: ");
        sentence = ent.nextLine();
        
        // 处理空输入
        if(sentence.length() == 0){
            System.out.println("You haven't written anything, exiting the program...");
            System.exit(0);
        }

        // 用subString拆分单词的核心逻辑
        int startIndex = 0;
        int spaceIndex;
        
        // 循环查找空格,直到找不到为止
        while ((spaceIndex = sentence.indexOf(' ', startIndex)) != -1) {
            // 截取从startIndex到空格位置的单词
            String word = sentence.substring(startIndex, spaceIndex);
            System.out.println(word);
            // 更新起始位置为空格的下一个字符
            startIndex = spaceIndex + 1;
        }
        
        // 处理最后一个单词(循环结束后剩下的部分)
        String lastWord = sentence.substring(startIndex);
        System.out.println(lastWord);
    }
}

代码解释

  • startIndex:记录每个单词的起始位置,初始为0(字符串第一个字符的索引)
  • sentence.indexOf(' ', startIndex):从startIndex开始查找空格的位置,找不到时返回-1,作为循环结束的标志
  • sentence.substring(startIndex, spaceIndex):截取从startIndex到空格位置的子串,就是一个完整的单词
  • 循环结束后,剩下的从startIndex到字符串末尾的部分就是最后一个单词,直接截取打印

额外优化(可选)

如果要处理句子中多个连续空格的情况,可以在循环里加判断跳过无效空格:

while ((spaceIndex = sentence.indexOf(' ', startIndex)) != -1) {
    // 跳过连续空格,只截取非空的单词
    if (startIndex != spaceIndex) {
        String word = sentence.substring(startIndex, spaceIndex);
        System.out.println(word);
    }
    startIndex = spaceIndex + 1;
}
// 最后也要判断是否为空(比如句子结尾有空格的情况)
String lastWord = sentence.substring(startIndex);
if (!lastWord.isEmpty()) {
    System.out.println(lastWord);
}

内容的提问来源于stack exchange,提问作者Eric Quevedo Carles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:55:19