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

为何str.trim()无法移除特定单词的全部空白符?Java解析类汇编代码疑问

Parsing Assembly-Like Code into a Java Array

Hey there! Let’s work through refining your assembly-like code parsing workflow. You’ve already nailed the first critical step—reading lines from the text file into a String array while preserving whitespace is a solid foundation. Now, let’s fix up the splitting and trimming logic to avoid common pitfalls and get clean, structured data.

Common Issues with Basic split(" ")

Using str.split(" ") directly can create annoying empty strings in your results, especially if lines have consecutive spaces, leading, or trailing whitespace. For example, a line like MOV R1, R2 #Load value would split into ["MOV", "", "R1,", "R2", "", "#Load", "value"]—those empty entries are just noise we don’t need.

Use split("\\s+") to split on one or more whitespace characters (spaces, tabs, etc.). This automatically skips consecutive gaps and avoids empty elements. Here’s a full implementation:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class AssemblyParser {
    public static void main(String[] args) {
        // Example pre-loaded lines from your file
        String[] lines = {
            "MOV  R1, R2  #Load register value",
            "ADD  R3, R1",
            "STORE R4  0x100"
        };

        List<List<String>> parsedInstructions = new ArrayList<>();

        for (String line : lines) {
            // Split on one or more whitespace characters
            String[] rawParts = line.split("\\s+");
            // Trim each part (extra safe, though split("\\s+") already removes surrounding whitespace)
            List<String> trimmedParts = Arrays.stream(rawParts)
                                             .map(String::trim)
                                             .collect(Collectors.toList());
            parsedInstructions.add(trimmedParts);
        }

        // Convert to a 2D String array if needed for your use case
        String[][] parsedArray = parsedInstructions.stream()
                                                   .map(list -> list.toArray(new String[0]))
                                                   .toArray(String[][]::new);

        // Verify the result
        for (String[] instruction : parsedArray) {
            System.out.println(Arrays.toString(instruction));
        }
    }
}

Solution 2: Filter Empty Strings After Splitting

If you specifically need to split on single spaces (for edge cases where single spaces hold meaning), split with split(" ") then filter out empty strings after trimming:

for (String line : lines) {
    String[] rawParts = line.split(" ");
    List<String> trimmedParts = Arrays.stream(rawParts)
                                     .map(String::trim)
                                     .filter(part -> !part.isEmpty()) // Remove empty entries
                                     .collect(Collectors.toList());
    parsedInstructions.add(trimmedParts);
}

Bonus: Preserve Entire Comments as Single Elements

If your assembly code uses comments (e.g., starting with #), you might want to keep each comment as a single element instead of splitting it into words. Here’s how to handle that:

for (String line : lines) {
    // Split line into instruction and comment sections (max 2 parts total)
    String[] lineSegments = line.split("#", 2);
    
    // Process the instruction part
    String instructionSegment = lineSegments[0].trim();
    List<String> instructionParts = Arrays.stream(instructionSegment.split("\\s+"))
                                         .filter(part -> !part.isEmpty())
                                         .collect(Collectors.toList());
    
    // Add the full comment as one element if it exists
    if (lineSegments.length > 1) {
        String comment = "#" + lineSegments[1].trim();
        instructionParts.add(comment);
    }
    
    parsedInstructions.add(instructionParts);
}

This turns a line like MOV R1, R2 #Load value into R2 into ["MOV", "R1,", "R2", "#Load value into R2"], keeping the comment intact as a single entry.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:19:29