[英]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"
. 我想删除换行符之后的所有内容,所以我想要的字符串将只是
"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
. 这将在第一个新行字符处分割您的字符串,并返回第一个子字符串,即
\\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)
如果您的新行是
\\n\\r
则使用重载的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.*;
并且您可能知道需要
import java.util.*;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.