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

时间:2014-09-29 22:07:43

标签: java regex oop split

我有一个字符串[] = [5 5,1 2 N,LMLMLMLMM,3 3 E,MMRMMRMRRM]

当我拆分第2和第4个元素时。我得到了

[, L, M, L, M, L, 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);

}

我试过更换空的空间,但没有用。如何在不返回空的第一个元素的情况下split()?

1 个答案:

答案 0 :(得分:3)

String.split()采用正则表达式,因此它可能无法以您期望的方式运行,但是如果您想使用它,则可以执行此操作:

System.out.println(Arrays.toString("LMLMLMLMM".split("(?!^)")));

哪个输出:

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

Here是对正则表达式的解释:

(?!^) 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()两者都可以使用双字节字符,所以最后它归结为可读性。