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
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.