我需要将输入字符串分成很多部分。拆分应在“ \ n”处发生(字面反斜杠为-n,而不是换行符)。例如,我想转这个:
x = [2,0,5,5]\ny = [0,2,4,4]\ndraw y #0000ff\ny = y & x\ndraw y #ff0000
到这个:
x = [2,0,5,5]
y = [0,2,4,4]
draw y #0000ff
y = y & x
draw y #ff0000
我本以为stringArray = string.split("\n");
就足够了。
但是它为我提供了与以下代码中的输入相同的输出:
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Input\n");
String s = br.readLine();
NewInterpreter interpreter = new NewInterpreter(s);
interpreter.run();
}
public NewInterpreter(String input) {
this.input = input;
this.index = 0;
this.inputComponents = input.split("\n");
System.out.println("Output: ");
for(String s : inputComponents)
System.out.println(s);
}
Enter Input
x = [2,0,5,5]\ny = [0,2,4,4]\ndraw x #00ff00\ndraw y #0000ff\ny = y & x\ndraw y #ff0000"
Output:
x = [2,0,5,5]\ny = [0,2,4,4]\ndraw x #00ff00\ndraw y #0000ff\ny = y & x\ndraw y #ff0000
非常感谢任何帮助,谢谢!
如果您按\n
字面意思输入(即与换行符相对),则需要按以下方式拆分:
string.split("\\\\n");
复杂性的原因是split()
需要使用正则表达式作为参数。当尝试使用正则表达式匹配文字反斜杠时,需要对其进行两次转义(一次用于正则表达式,一次用于字符串文字)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句