-1
public class Test {
    
    public static void main(String[] args) {
        
        String paragh = "Twinkle, twinkle, little star\r\n"
                + "How I wonder what you are\r\n"
                + "Up above the world so high\r\n"
                + "Like a diamond in the sky\r\n"
                + "Twinkle, twinkle, little star\r\n"
                + "How I wonder what you are";
        
        String firstLine; // the first line should be derived from the paragh
        
    }

}

Now what should i do to make paragh's first line in the firstLine String?

Codebling
  • 10,764
  • 2
  • 38
  • 66
Sandy
  • 1
  • 1

2 Answers2

2

Option 1: split

Split the string by the \r\n delimiter with paragh.split("\r\n"). Then the first array element is the first line:

String[] portions = paragh.split("\r\n", 2);
String firstLine = portions[0];

Note that we need only the first line. So one we have it, we don't need to look for more lines. That's why the second argument (limit) is set to 2.

Option 2: indexOf and substring

indexOf returns the first position the given substring is found. Once we have that index, we could return a portion of paragh from index 0 to that index:

int pos = paragh.indexOf("\r\n");
if (pos != -1) {
    firstLine = paragh.substring(0, pos);
}
else {
    firstLine = paragh;
}

Note that indexOf returns the sentinel value -1 if the substring \r\n was not found, i.e. when there's only one line. If there's only one line, then we could as well return the whole string.


Shorter versions of the code snippets:
• 1. String firstLine = paragh.split("\r\n", 2)[0]
• 2. int pos = paragh.indexOf("\r\n"); String firstLine = (pos == -1 ? paragh : paragh.substring(0, pos));

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
0
String firstLine = paragh.split("\n")[0];
System.out.println(firstLine);
hous
  • 92
  • 1
  • 11