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

前端 未结 10 1029
醉酒成梦
醉酒成梦 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();
    

提交回复
热议问题