Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim a string after a specific character in java

Tags:

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,

like image 539
user2430771 Avatar asked Aug 13 '13 22:08

user2430771


People also ask

How do I remove a string after a specific character in Java?

The deleteCharAt() method is a member method of the StringBuilder class that can also be used to remove a character from a string in Java. To remove a particular character from a string, we have to know that character's position if we want to remove that character using the deleteCharAt method.

How do I remove all characters from a string after a specific character?

Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); .

How do you remove all characters before a certain character from a string in Java?

. trim() removes spaces before the first character (which isn't a whitespace, such as letters, numbers etc.) of a string (leading spaces) and also removes spaces after the last character (trailing spaces). If there are multiple = you can get the index of the last occurrence with s.


2 Answers

You can use:

result = result.split("\n")[0]; 
like image 195
Nir Alfasi Avatar answered Oct 14 '22 23:10

Nir Alfasi


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

like image 22
arshajii Avatar answered Oct 15 '22 00:10

arshajii