Split Java String by New Line

前端 未结 20 1088
予麋鹿
予麋鹿 2020-11-22 00:56

I\'m trying to split text in a JTextArea using a regex to split the String by \\n However, this does not work and I also tried by \\r\\n|\\r|

20条回答
  •  温柔的废话
    2020-11-22 01:53

    There is new boy in the town, so you need not to deal with all above complexities. From JDK 11 onward, just need to write as single line of code, it will split lines and returns you Stream of String.

    public class MyClass {
    public static void main(String args[]) {
       Stream lines="foo \n bar \n baz".lines();
       //Do whatever you want to do with lines
    }}
    

    Some references. https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#lines() https://www.azul.com/90-new-features-and-apis-in-jdk-11/

    I hope this will be helpful to someone. Happy coding.

提交回复
热议问题