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

前端 未结 10 984
醉酒成梦
醉酒成梦 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:30

    You could use :

    BufferedReader bufReader = new BufferedReader(new StringReader(textContent));
    

    And use the readLine() method :

    String line=null;
    while( (line=bufReader.readLine()) != null )
    {
    
    }
    
    0 讨论(0)
  • 2020-12-25 10:32

    To add the Java 8 way to this question:

    Arrays.stream(content.split("\\r?\\n")).forEach(line -> /*do something */)
    

    Of curse you can also use System.lineSeparator()to split if you are sure that the file is comming from the same plattform as the vm runs on.

    Or even better use the stream api even more agressiv with filter, map and collect:

    String result = Arrays.stream(content.split(System.lineSeparator()))
                         .filter(/* filter for lines you are interested in*/)
                         .map(/*convert string*/)
                         .collect(Collectors.joining(";"));
    
    0 讨论(0)
  • 2020-12-25 10:32

    Combine java.io.StringReader and java.io.LineNumberReader

    0 讨论(0)
  • 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<String> 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
    
    0 讨论(0)
提交回复
热议问题