我有一个字符串[] = [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);
}
我尝试替换空白空间,但无济于事。如何在不返回此空的第一个元素的情况下split()?
String.split()
采用正则表达式,因此它可能无法按您期望的方式运行,但是,如果要使用它,可以执行以下操作:
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()
两者都可以使用双字节字符,因此最终归结为可读性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句