What is the best way to iterate over the lines of a Java String?

前端 未结 10 1028
醉酒成梦
醉酒成梦 2020-12-25 09:45

Currently I\'m using something like :

String[]lines = textContent.split(System.getProperty(\"line.separator\"));
for(String tmpLine : lines){
   //do somethi         


        
10条回答
  •  轮回少年
    2020-12-25 10:36

    You can actually wrangle Scanner to allow you to use a normal for loop:

    import java.util.Scanner;
    public class IterateLines {
        public static void main(String[] args) {
            Iterable sc = () ->
                new Scanner("foo bar\nbaz\n").useDelimiter("\n");
            for (String line: sc) {
                System.out.println(line);
            }
        }
    }
    

    gives us:

    $ javac IterateLines.java && java IterateLines 
    foo bar
    baz
    

提交回复
热议问题