Java split()返回的第一个元素为空

Java split()返回的第一个元素为空,java,regex,oop,split,Java,Regex,Oop,Split,我有一个字符串[]=[55,12N,LMM,33E,MMRMMRRM] 当我分割第二和第四元素时。我明白了 [,L,M,L,M,L,M,M,L,M,M] [,M,M,R,M,M,R,M,R,R,M] import java.io.*; public class Instruction { public String[] instructionList; public String filePath; public Instruction(String fileName) { this

我有一个字符串[]=[55,12N,LMM,33E,MMRMMRRM]

当我分割第二和第四元素时。我明白了


[,L,M,L,M,L,M,M,L,M,M]

[,M,M,R,M,M,R,M,R,R,M]

import java.io.*;

public class Instruction {
public String[] instructionList;
public String filePath;

public Instruction(String fileName) {
    this.filePath = fileName;
}

public String[] readFile() throws IOException {
    FileInputStream in = new FileInputStream(this.filePath);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));

    int n = 5;
    instructionList = new String[n];

    for (int j = 0; j < instructionList.length; j++) {
        instructionList[j] = br.readLine();
    }
    in.close(); 
    return instructionList;
}}

import java.util.Arrays;
public class RoverCommand {

public static void main(String[] args) throws Exception {

//Create new Instruction object with directions.txt.                
    Instruction directions = new Instruction("directions.txt");
    String[] instructions = directions.readFile();              
    String roverInstructions = Arrays.toString(instructions[2].split(""));
    System.out.println(roverInstructions);
import java.io.*;
公共课堂教学{
公共字符串[]指令列表;
公共字符串文件路径;
公共指令(字符串文件名){
this.filePath=文件名;
}
公共字符串[]readFile()引发IOException{
FileInputStream in=新的FileInputStream(this.filePath);
BufferedReader br=新的BufferedReader(新的InputStreamReader(in));
int n=5;
指令列表=新字符串[n];
对于(int j=0;j
}

我已尝试替换空白,但无效。如何在不返回第一个空元素的情况下拆分()呢?

String。拆分()
采用正则表达式,因此它可能无法按预期方式运行,但是如果要使用它,可以执行以下操作:

System.out.println(Arrays.toString("LMLMLMLMM".split("(?!^)")));
哪个输出:

[L, M, L, M, L, M, L, M, M]
是对正则表达式的解释:

(?!^) Negative Lookahead - Assert that it is impossible to match the regex below
   ^ assert position at start of the string
这将为您提供相同的输出:

System.out.println(Arrays.toString("LMLMLMLMM".toCharArray()));

在这种情况下,我支持
toCharArray()
两者都可以使用双字节字符,因此最终还是要看可读性。

也许您愿意向我们展示您的拆分语句?拆分的参数是什么?
请显示所有相关代码。拆分第二个和第四个元素是什么意思?@sin当我读取文件“directions.txt”时,返回的是一个字符串[5,1,2 N,lmlmm,3,3 E,mmrmmrrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrm]中的[]为什么不这样使用
System.out.println(Arrays.toString(“lmlmlmm.toCharArray());
[L,M,M,M,L,M,L,M,M]
OP的拆分行可以得到什么输出?:)
System.out.println(Arrays.toString(“lmm.split”));
[,L,M,L,M,M,M,L,M,M]
这里我得到了预期的输出…没有第一个空元素..使用相同的代码行。我无法解释为什么你会有这种经验。你使用的是什么版本的Java?