简体   繁体   中英

Java - Trim string after newline

My string is say :

str1="ash
def";

I want to remove anything after the newline so my desired string would be only "ash" .

How do I do this, One thing could be I could trim this and then substring it . Any other ways which I can do this.

Thanks

Try this:

System.out.println(str1.split("\n")[0]);  

This will split your string at first new line character and return first substring ie before \\n .

You can use substring

String firstPart = str1.substring(0, str1.indexOf('\n'));
System.out.println(firstPart);

in contrast to

str.split("\n")[0]

the substring approach is faster, because

  • split uses regexp to find the delimiter
  • split creates at least 3 new objects. The returned array and the strings at the array indexes 0 and 1, but you only need the string at 0.

If your new line is \\n\\r then use the overloaded String.indexOf(String)

String str1 = "ash\n\rdef";
System.out.println(str1.substring(0, str1.indexOf("\n\r")));

\\n分割并选择第一个元素

str.split("\n")[0]

Following is another way to do this:

StringTokenizer st=new StringTokenizer("ash\ndef","\n");

System.out.println(st.nextToken());

and as you might be knowing you need to import java.util.*;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM