Open In App

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

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Java




// Java program to extract a specific line from a multi-line String
import java.util.Scanner;
  
public class Get_specific_line_from_multiline {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String Multi_line_string = "She is a very good girl\n"
                + "Also, she is very intelligent.\n"
                + "She got the first prize.\n"
                + "She will definitely make her parents proud.\n";
  
        // Display the original multi-line string
        System.out.println("Original String is : ");
        System.out.println(Multi_line_string);
  
        // Line number to extract from the multi-line string
        int line = 3;
  
        // Extract the specific line
        String ans = extractLine(Multi_line_string, line);
  
        // Display the extracted line
        System.out.println("The Specific line is : " + ans);
    }
  
    // Method to extract a specific line from a multi-line string
    private static String extractLine(String input, int line) {
        String[] arrOfstr = input.split("\n");
        if (arrOfstr.length >= line)
            return arrOfstr[line - 1];
        return "";
    }
}


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.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads