How to trim a string after a specific character in

2020-05-21 08:02发布

I have a string variable in java having value:

String result="34.1 -118.33\n<!--ABCDEFG-->";

I want my final string to contain the value:

String result="34.1 -118.33";

How can I do this? I'm new to java programming language.

Thanks,

标签: java
9条回答
Fickle 薄情
2楼-- · 2020-05-21 08:34

How about

Scanner scanner = new Scanner(result);
String line = scanner.nextLine();//will contain 34.1 -118.33
查看更多
叛逆
3楼-- · 2020-05-21 08:41

Use regex:

result = result.replaceAll("\n.*", "");

replaceAll() uses regex to find its target, which I have replaced with "nothing" - effectively deleting the target.

The target I've specified by the regex \n.* means "the newline char and everything after"

查看更多
smile是对你的礼貌
4楼-- · 2020-05-21 08:43

Assuming you just want everything before \n (or any other literal string/char), you should use indexOf() with substring():

result = result.substring(0, result.indexOf('\n'));

If you want to extract the portion before a certain regular expression, you can use split():

result = result.split(regex, 2)[0];

String result = "34.1 -118.33\n<!--ABCDEFG-->";

System.out.println(result.substring(0, result.indexOf('\n')));
System.out.println(result.split("\n", 2)[0]);
34.1 -118.33
34.1 -118.33

(Obviously \n isn't a meaningful regular expression, I just used it to demonstrate that the second approach also works.)

查看更多
成全新的幸福
5楼-- · 2020-05-21 08:46

Try this:

String result = "34.1 -118.33\n<!--ABCDEFG-->";
result = result.substring(0, result.indexOf("\n"));
查看更多
爱情/是我丢掉的垃圾
6楼-- · 2020-05-21 08:47

There are many good answers, but I would use StringUtils from commons-lang. I find StringUtils.substringBefore() more readable than the alternatives:

String result = StringUtils.substringBefore("34.1 -118.33\n<!--ABCDEFG-->", "\n");
查看更多
祖国的老花朵
7楼-- · 2020-05-21 08:47

You could use result = result.replaceAll("\n",""); or

 String[] split = result.split("\n");
查看更多
登录 后发表回答