gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:20:23 30 4
gpt4 key购买 nike

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

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

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

我试过替换空白区域,但无济于事。如何在不返回这个空的第一个元素的情况下拆分()?

最佳答案

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

关于Java split() 返回一个空的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26109688/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com