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

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

    Scanner

    What about the java.util.Scanner class added in Java 1.5?

    In summary:

    A simple text scanner which can parse primitive types and strings using regular expressions.

    A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

    and of note for your scenario:

    The scanner can also use delimiters other than whitespace. This example reads several items in from a string:

         String input = "1 fish 2 fish red fish blue fish";
         Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
         System.out.println(s.nextInt());
         System.out.println(s.nextInt());
         System.out.println(s.next());
         System.out.println(s.next());
         s.close();
    
    0 讨论(0)
  • 2020-12-25 10:11

    use BufferedReader with StringReader argument. BufferedReader has a method readLine() so you can read your string line by line.

        StringReader reader = new StringReader(myBigTextString);
        BufferedReader br = new BufferedReader(reader);
        String line;
        while((line=br.readLine())!=null)
        {
            //do what you want
        }
    
    0 讨论(0)
  • 2020-12-25 10:21

    I believe you have a better API available starting with Java-11 where you can do the same using the String.lines() API which returns the stream of strings extracted from this string partitioned by line terminators.

    public Stream<String> lines()
    

    Usage of the same could be:-

    Stream<String> linesFromString = textContent.lines();
    linesFromString.forEach(l -> {  //do sth });
    

    Important API Note :-

    @implNote This method provides better performance than
              split("\R") by supplying elements lazily and
              by faster search of new line terminators.
    
    0 讨论(0)
  • 2020-12-25 10:21

    Guava's Splitter works well. Especially as you can remove blank lines

    Splitter splitter = Splitter.on(System.getProperty("line.separator"))
                                .trimResults()
                                .omitEmptyStrings();
    for (String line : splitter.split(input)){
       // do work here
    }
    
    0 讨论(0)
  • 2020-12-25 10:21

    If you are using Java 1.8 (or Android) then try this:

    new BufferedReader(new StringReader(str)).lines().forEachOrdered((line) -> {
        // process each line as you like
    });
    

    Docs state

    The Stream is lazily populated, i.e., read only occurs during the terminal stream operation.

    Which means this runs quicker than other solutions that first generate a massive array of Strings before iteration can begin.

    If you are using Java 11 or later then the answer @Naman gave recommending String#lines() method is even cleaner and fast as well, see https://stackoverflow.com/a/50631579/215266

    0 讨论(0)
  • 2020-12-25 10:22

    You could use String.indexOf()/String.substring()

    String separator = System.getProperty("line.separator");
    int index = textContent.indexOf(separator);
    
    while (index > 0)
    {
      int nextIndex = textContent.indexOf(separator, index + separator.length());
      String line = textContent.substring(index + separator.length(), nextIndex);
    
      // do something with line.
    }
    
    0 讨论(0)
提交回复
热议问题