Having problems using myString.split(“\n”);

丶灬走出姿态 提交于 2019-12-23 07:02:17

问题


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

into this:

x = [2,0,5,5]
y = [0,2,4,4]
draw y #0000ff
y = y & x
draw y #ff0000

I would have thought that stringArray = string.split("\n"); would have been sufficient.

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!


回答1:


If you're entering \n literally (i.e. as opposed to as a newline character), you need to split as follows:

string.split("\\\\n");

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).




回答2:


There can't be any linefeeds in text you read via readLine().

Ergo you must be looking for literal \ followed by a literal n. (Why?)

Ergo you must provide two backslashes for the regular expression compiler, and you will have to escape them both once each for the Java compiler. Total: four.

Alternatively you are just attempting the impossible, trying to split on linefeeds that aren't there. Maybe the input is already split adequately by just calling readLine()?



来源:https://stackoverflow.com/questions/29886583/having-problems-using-mystring-split-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!