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,
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,
How about
Use regex:
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"Assuming you just want everything before
\n
(or any other literal string/char), you should useindexOf()
withsubstring()
:If you want to extract the portion before a certain regular expression, you can use
split()
:(Obviously
\n
isn't a meaningful regular expression, I just used it to demonstrate that the second approach also works.)Try this:
There are many good answers, but I would use
StringUtils
from commons-lang. I findStringUtils.substringBefore()
more readable than the alternatives:You could use
result = result.replaceAll("\n","");
or