[英]How to Split string in java using “\n”
I am taking a command line input string like this: 我正在使用这样的命令行输入字符串:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
I want to split this string which is: 我想分割此字符串,即:
String line = "int t; //variable t
t->a = 0; //t->a does something
return 0;"
like this: 像这样:
String[] arr = line.split("\n");
arr[0] = "int t; //variable t";
arr[1] = "t->a=0; //t->a does something";
arr[2] = "return 0";
but when i run my java program that split function only returns this: 但是当我运行我的java程序时,split函数只会返回以下内容:
arr[0] = "int t; //variable t";
it didn't returns other two strings that i mentioned above,why this is happening please explain. 它没有返回我上面提到的其他两个字符串,为什么会发生这种情况,请解释一下。
The method readLine()
will read the input until a new-line character is entered . readLine()
方法将读取输入, 直到输入换行符为止 。 That new-line character is "\\n"
. 该换行符为
"\\n"
。 Therefore, it won't ever read the String
separated by "\\n"
. 因此,它将永远不会读取以
"\\n"
分隔的String
。
One solution: 一种解决方案:
You can read the lines with a while
loop and store them in an ArrayList
: 您可以使用
while
循环读取这些行并将其存储在ArrayList
:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
List<String> lines = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
for (String s : lines) {
System.out.println(s);
}
To stop the while
you will have to press Ctrl + z (or Ctrl + d in UNIX, if I'm not wrong). 要停止片刻
while
您必须按Ctrl + z (或UNIX中的Ctrl + d ,如果我没有记错的话)。
这应该可行!还要确保您的输入内容是否包含\\n
String[] arr = line.split("\r?\n")
From your comment you seem to take the input like this 根据您的评论,您似乎接受了这样的输入
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
Here the line
represents already split string by \\n
. 这里的
line
表示已经用\\n
分割的字符串。 When you hit enter on the console, the text entered in one line gets captured into line
. 当您在控制台上按Enter键时,在一行中输入的文本将被捕获到
line
。 As per me you are reading line, only once which captures just int t;//variable t
, where there is nothing to split. 就我而言,您正在阅读一行, 仅捕获一次
int t;//variable t
,其中没有任何可分割的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.