简体   繁体   English

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

[英]Java split() is returning an empty first element

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

When I split the 2nd and 4th elements. 当我分割第二和第四元素时。 I get 我懂了

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

} }

I've tried replacing the empty space, to no avail. 我尝试替换空白空间,但无济于事。 How can I split() without returning this empty first element? 如何在不返回此空的第一个元素的情况下split()?

String.split() takes a regular expression so it may not be operating the way you are expecting it, however if you wanted to use it you could do this: String.split()采用正则表达式,因此它可能无法按照您期望的方式运行,但是,如果您想使用它,可以这样做:

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

Which outputs this: 输出以下内容:

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

Here is a explanation of the regular expression: 是正则表达式的解释:

(?!^) Negative Lookahead - Assert that it is impossible to match the regex below
   ^ assert position at start of the string

This will give you the same output though: 但是,这将为您提供相同的输出:

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

In this case I would advocate for toCharArray() both will work with double byte chars, so in the end it comes down to readability. 在这种情况下,我主张toCharArray()都可以使用双字节字符,因此最终归结为可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM