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

如何统计字符串数组中每个单词的字母数?求技术技巧与方法建议

解决字符串单词长度统计的问题

Hey there! Let's work through your problem with counting letter lengths for words in strings, plus fix up that code you started writing.

实用技巧总结

  • 拆分字符串更高效:如果是处理整句(比如你的"Here is just an example"),用split("\\s+")把句子拆成单词数组——这个正则表达式能匹配任意数量的空白字符,避免多个空格导致的空字符串元素。
  • 直接用length()方法:Java的String类自带length()方法,直接调用就能得到单词的字符数,比手动遍历计数靠谱多了,还能少写bug。
  • 按需处理特殊情况:如果单词里混了标点,只想统计纯字母数,可以先用replaceAll("[^a-zA-Z]", "")过滤掉非字母字符,再取长度;遇到空字符串或null值,记得加判断避免报错。

关于整数转字符串的问题

当然可以用!当你拿到单词长度(整数类型)后,有几种简单的转换方式:

  • String.valueOf(length):最规范的写法
  • length + "":更简洁的语法糖,底层其实也是调用String.valueOf()

两种都能帮你把数字转成字符串,方便拼接成"Here-4"这种格式。

修正你的代码

你原来的代码有几个明显的问题:比如用了空字符串s遍历、变量名重复、逻辑没关联输入数组,而且返回二维数组其实没必要——我们直接返回格式正确的字符串数组或者拼接好的字符串就行。

情况1:处理单个句子字符串

如果你要处理像"Here is just an example"这样的整句,代码可以写成这样:

public class WordLengthDemo {
    public static void main(String[] args) {
        String s = "Here is just an example";
        String[] words = s.split("\\s+"); // 拆分单词,兼容多空格
        StringBuilder resultBuilder = new StringBuilder();

        for (String word : words) {
            int wordLength = word.length();
            // 拼接成"单词-长度"格式,用空格分隔
            resultBuilder.append(word).append("-").append(wordLength).append(" ");
        }

        // 去掉末尾多余的空格再输出
        if (resultBuilder.length() > 0) {
            resultBuilder.setLength(resultBuilder.length() - 1);
        }
        System.out.println(resultBuilder);
        // 输出结果:Here-4 is-2 just-4 an-2 example-7
    }
}

情况2:处理字符串数组(你的方法参数类型)

如果你的输入是String[](每个元素是一个单词),可以调整成这样的方法:

private static String[] getWordLengths(String[] wordArray) {
    String[] resultArray = new String[wordArray.length];

    for (int i = 0; i < wordArray.length; i++) {
        String currentWord = wordArray[i];
        // 处理null或空字符串的情况
        if (currentWord == null || currentWord.isEmpty()) {
            resultArray[i] = "empty-0";
            continue;
        }
        int length = currentWord.length();
        // 整数转字符串并拼接格式
        resultArray[i] = currentWord + "-" + String.valueOf(length);
    }
    return resultArray;
}

// 调用示例
public static void main(String[] args) {
    String[] input = {"Here", "is", "just", "an", "example"};
    String[] output = getWordLengths(input);
    for (String item : output) {
        System.out.print(item + " ");
    }
    // 输出:Here-4 is-2 just-4 an-2 example-7 
}

额外优化提示

如果需要统计纯字母的长度(排除标点、数字),把int length = currentWord.length();改成:

int letterOnlyLength = currentWord.replaceAll("[^a-zA-Z]", "").length();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:07:17