使用myString.split(" \ n")时遇到问题; [英] Having problems using myString.split("\n");
问题描述
我需要将输入字符串分成许多部分。拆分应该出现在\ n(字面上反斜杠-n,而不是换行符)。
例如,我想转此:
I need to split an input string into many parts. The splits should occur at "\n" (literally backslash-n, not the newline character). E.g., I want to turn this:
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);
就足够了。
但是它给了我与输入相同的输出下面的代码:
But it gives me the same output as input in the following code:
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
任何帮助都很大谢谢,谢谢!
Any help is greatly appreciated, thanks!
推荐答案
如果您输入 \ n
字面上(即与换行符相对),您需要按如下方式拆分:
If you're entering \n
literally (i.e. as opposed to as a newline character), you need to split as follows:
string.split("\\\\n");
复杂的原因是 split()
将正则表达式作为参数。当尝试使用正则表达式匹配文字反斜杠时,需要对其进行双重转义(一次用于正则表达式,一次用于字符串)文字)。
The reason for the complexity is that split()
takes a regular expression as an argument. When trying to match a literal backslash using a regular expression, it needs to be doubly escaped (once for the regular expression, and once for the string literal).
这篇关于使用myString.split(" \ n")时遇到问题;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!