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

Java:如何解决字符串单词存入数组问题以实现指定长度单词筛选

Java方法实现:提取指定长度的单词数组

需求说明

输入一个由空格分隔单词的句子字符串,以及一个代表目标单词长度的数字,返回包含所有符合该长度的单词的字符串数组。示例如下:

String s = "Monday is a new day";
int n = 3; // 筛选3个字母的单词
howManyWord(s, n) 返回 {"new", "day"}
howManyWord(s, 2) 返回 {"is"}

问题描述

以下代码中,第二个for循环无法正确将单词赋值到数组中,请求解决:

public String[] howManyWord(String s, int n) {
        //count the amount of words in the String
        int counter1 = 0;
        for(int a1 = 1; a1 < s.length(); a1++) {
          char c1 = s.charAt(a1-1);
          char c2 = s.charAt(a1);
          if(c1 != ' ' && c2 == ' '){
              counter1++;
          }
        }

        counter1 += 1;
        //Get the words of a string into an array + the loop in question
        String[] words = new String[counter1];
        String[] output = new String[counter1];
        for(int a2 = 1; a2 < s.length(); a2++) {
            char c1 = s.charAt(a2-1);
          char c2 = s.charAt(a2);
          int counter2 = 0;
          if(c1 != ' ' && c2 == ' '){
              int index1 = s.indexOf(c1);
              int index2 = s.indexOf(c2);
              words[counter2] = s.substring(index1, index2);
                  counter2++;
          }
        }

        //assign words of a specific length into output array
        for(int a3 = 0; a3 < output.length; a3++) {
           if(words[a3].length() == n){
               output[a3] = words[a3];
           }
        }
        return output;
        }

问题分析

  1. 第二个循环的核心错误:
    • counter2定义在循环内部,每次循环都会重置为0,导致永远只能给words[0]赋值
    • s.indexOf(c1)返回的是字符c1第一次出现的索引,不是当前单词的起始位置,逻辑完全错误
  2. 其他潜在问题:
    • 未处理字符串首尾空格,会导致单词计数错误
    • 最后一个单词后面没有空格,循环无法捕获,会丢失该单词
    • 结果数组output长度等于总单词数,最终会包含大量null值,不符合返回要求

解决方案

方案一:用Java标准库简化实现(推荐)

直接使用split分割字符串,配合循环或Stream过滤符合长度的单词,代码简洁高效:

import java.util.Arrays;

public String[] howManyWord(String s, int n) {
    // 去除首尾空格,按任意空白符分割(处理多个连续空格的情况)
    String[] allWords = s.trim().split("\\s+");
    
    // 统计符合长度的单词数量
    int validCount = 0;
    for (String word : allWords) {
        if (word.length() == n) {
            validCount++;
        }
    }
    
    // 填充结果数组
    String[] result = new String[validCount];
    int index = 0;
    for (String word : allWords) {
        if (word.length() == n) {
            result[index++] = word;
        }
    }
    return result;
}

如果使用Java 8及以上版本,还可以用Stream更简洁地实现:

import java.util.Arrays;

public String[] howManyWord(String s, int n) {
    return Arrays.stream(s.trim().split("\\s+"))
                 .filter(word -> word.length() == n)
                 .toArray(String[]::new);
}

方案二:修正原始代码逻辑

如果要保留原始的字符遍历思路,修正后的代码如下:

public String[] howManyWord(String s, int n) {
    // 先去除首尾空格,避免计数错误
    s = s.trim();
    if (s.isEmpty()) {
        return new String[0];
    }
    
    // 统计单词数量
    int counter1 = 0;
    for (int a1 = 1; a1 < s.length(); a1++) {
        char c1 = s.charAt(a1 - 1);
        char c2 = s.charAt(a1);
        if (c1 != ' ' && c2 == ' ') {
            counter1++;
        }
    }
    counter1 += 1;

    // 提取所有单词到数组
    String[] words = new String[counter1];
    int counter2 = 0;
    int startIndex = 0; // 记录当前单词的起始索引
    for (int a2 = 1; a2 < s.length(); a2++) {
        char c1 = s.charAt(a2 - 1);
        char c2 = s.charAt(a2);
        if (c1 != ' ' && c2 == ' ') {
            // 截取当前单词(从startIndex到空格位置a2)
            words[counter2] = s.substring(startIndex, a2);
            counter2++;
            // 更新下一个单词的起始索引为空格的下一位
            startIndex = a2 + 1;
        }
    }
    // 处理最后一个单词(循环结束后,startIndex到字符串末尾是最后一个单词)
    words[counter2] = s.substring(startIndex);

    // 统计符合长度的单词并填充结果数组
    int resultCount = 0;
    for (String word : words) {
        if (word.length() == n) {
            resultCount++;
        }
    }
    String[] output = new String[resultCount];
    int outputIndex = 0;
    for (String word : words) {
        if (word.length() == n) {
            output[outputIndex++] = word;
        }
    }
    return output;
}

内容的提问来源于stack exchange,提问作者Stablinz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:50:31