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

Java如何从长字符串中提取$与,包裹的整数值存入int数组

Java提取$与,包裹整数的实现方案

方案1:单次遍历原生实现(时间复杂度O(n),优化两次遍历问题)

你原来需要两次遍历是因为要先统计$的数量来固定数组长度,改用ArrayList<Integer>动态存储结果,就可以省略第一次统计遍历,全程只遍历一次字符串:

import java.util.ArrayList;
import java.util.Scanner;

class RandomStuff {
    public static void main (String[]args){
        Scanner keyboard = new Scanner(System.in);
        // 注意如果输入字符串包含空格,要改用nextLine()而不是next()
        String input = keyboard.nextLine();
        ArrayList<Integer> resultList = new ArrayList<>();
        StringBuilder numBuilder = new StringBuilder();
        boolean isCollecting = false;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c == '$') {
                // 遇到$开始收集数字,先清空历史缓存
                numBuilder.setLength(0);
                isCollecting = true;
            } else if (c == ',') {
                // 遇到,结束收集,转换为整数存入集合
                if (isCollecting && numBuilder.length() > 0) {
                    resultList.add(Integer.parseInt(numBuilder.toString()));
                    isCollecting = false;
                }
            } else if (isCollecting) {
                // 收集状态下拼接数字字符
                numBuilder.append(c);
            }
        }

        // 转换为你需要的int数组
        int[] intlist = resultList.stream().mapToInt(Integer::intValue).toArray();

        // 此处补充你自己的打印逻辑
        keyboard.close();
    }
}

该方案时间复杂度为严格的O(n),全程仅遍历字符串1次,空间复杂度为O(k),k为提取到的整数总长度。


方案2:正则表达式实现(代码更简洁,适合快速开发)

直接用正则匹配所有$数字,格式的片段,提取捕获组内的数字即可:

import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class RandomStuff {
    public static void main (String[]args){
        Scanner keyboard = new Scanner(System.in);
        String input = keyboard.nextLine();
        ArrayList<Integer> resultList = new ArrayList<>();
        // 正则规则:匹配$开头、逗号结尾的片段,中间数字作为捕获组
        Pattern pattern = Pattern.compile("\\$(\\d+),");
        Matcher matcher = pattern.matcher(input);
        while (matcher.find()) {
            resultList.add(Integer.parseInt(matcher.group(1)));
        }
        int[] intlist = resultList.stream().mapToInt(Integer::intValue).toArray();
        // 此处补充你自己的打印逻辑
        keyboard.close();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:06:04