how do you use string.trim() method to trim the white spaces only at the end ?
I mean without affecting the spaces at the front side
ex : input : " this is linkedin " o/p : " this is linkedin"
how do you use string.trim() method to trim the white spaces only at the end ?
I mean without affecting the spaces at the front side
ex : input : " this is linkedin " o/p : " this is linkedin"
Use regex:
str.replaceAll("\\s+$", "");
\s – any whitespace character
+ – match one or more whitespace character
$ – at the end of the string
You can read more from here.
There is no right-trim method, but you can do it via several workarounds. One consists of putting a non-blank character in the beginning of the String, trimming it and then removing the character. Using String.replaceAll() would allow you to do it with a regular expression.
I believe you cannot do that with trim()
.May be you can look for Apache commons which has an utility method StringUtils#stripEnd().
I haven't tested this , but hope it works for your purpose :
string = string.replaceAll("\\s+$", "");
Another solution would be to iterate through the char[]
obtained from the string in reverse and remove the unwanted characters !
If you necessarily have to use the trim() method,then this may be helpful:-
public class OP2 {
public static void main(String[] s) {
//object hash table
int index = 0;
String s1 = " sdfwf ";
for(int i=0;i<s1.length();i++)
{
if(s1.charAt(i)==' ')
index = index + 1;
else
break;
}
System.out.println(s1.substring(0,index)+ s1.trim());
}
}
In case, if the query was for .net language then you can use the built-in RTRIM method to achieve the same.
In .NET/C# you can use the TrimEnd method on your string object:
" this is linkedin ".TrimEnd();
public class RegexRemoveEnd {
public static String removeTrailingSpaces(String text) {
return text.replaceAll(" +$", "");
}
}