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,
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.
Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); .
. 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.
You can use:
result = result.split("\n")[0]; 
                        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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With