VOOZH about

URL: https://www.geeksforgeeks.org/java/extract-a-specific-line-from-a-multi-line-string-in-java/

⇱ How to Extract a Specific Line from a Multi-Line String in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Extract a Specific Line from a Multi-Line String in Java?

Last Updated : 14 Feb, 2024

In Java, String Plays an important role. As String stores or we can say it is a collection of characters. We want to get a specific line from a multi-line String in Java. This can also be done in Java.

In this article, we will be learning how to extract a specific line from a multi-line String in Java using extractLine() method.

extractLine(): This method extracts the specific line from the multiline string and stores the result in another string.

Program to Extract a Specific Line from a Multi-Line String in Java

Below is the implementation of extracting a specific line from a multiline string by using extractLine() and split() methods.


Output
Original String is : 
She is a very good girl
Also, she is very intelligent.
She got the first prize.
She will definitely make her parents proud.

The Specific line is : She got the first prize.

Explanation of the Program:

  • This Java program extracts a specific line from a multi-line string by splitting the string into an array of lines.
  • Then it retrieves the line at the specified index.
  • It uses the split() method to separate the multi-line string into individual lines based on the newline character (\n).
  • Then, it checks if the array length is sufficient to access the specified line.
  • Then it returns the line, otherwise, it returns an empty string.
  • This approach efficiently handles the task of extracting a particular line from a multi-line string in Java.
Comment