[java] How to trim a string after a specific character in java

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,

This question is related to java

The answer is


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


Try this:

String result = "34.1 -118.33\n<!--ABCDEFG-->";
result = result.substring(0, result.indexOf("\n"));

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

 String[] split = result.split("\n");

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");

How about

Scanner scanner = new Scanner(result);
String line = scanner.nextLine();//will contain 34.1 -118.33

you can use StringTokenizer:

StringTokenizer st = new StringTokenizer("34.1 -118.33\n<!--ABCDEFG-->", "\n");
System.out.println(st.nextToken());

output:

34.1 -118.33

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"


Use a Scanner and pass in the delimiter and the original string:

result = new Scanner(result).useDelimiter("\n").next();

This is the simplest method you can do and reduce your efforts. just paste this function in your class and call it anywhere:

you can do this by creating a substring.

simple exampe is here:

_x000D_
_x000D_
public static String removeTillWord(String input, String word) {
    return input.substring(input.indexOf(word));
}

removeTillWord("Your String", "\");
_x000D_
_x000D_
_x000D_