0

I just want to remove everything after a new line in a JAVA string. For Example:- If String = "Class Name Address"

I want my output to be = "Class"

It is not a String Array it is one String with 3 lines

Help would be highly appreciated.

Dony
  • 1

1 Answers1

0

Something like this?

public class Main {

  public static String firstLine(String s){
    if (s == null) return null;
    int cr = s.indexOf("\r");
    int nl = s.indexOf("\n");
    if (cr == -1 && nl == -1) return s;
    if (cr >= 0 && nl >= 0) return s.substring(0, Math.min(cr, nl));
    if (cr >= 0) return s.substring(0, cr);
    return s.substring(0, nl);
  }

  public static void main(String[] args){
    System.out.println(firstLine("line one"));
    System.out.println(firstLine("line one\r\nline two"));
    System.out.println(firstLine("line one\nline two"));
    System.out.println(firstLine("line one\r\nline two\r\nline three"));
    System.out.println(firstLine("line one\nline two\nline three"));
  }

}

Output is always: line one

Slawomir Chodnicki
  • 1,447
  • 9
  • 15