-3

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"

Ankur Lathi
  • 7,636
  • 5
  • 37
  • 49

8 Answers8

13

Use regex:

str.replaceAll("\\s+$", "");
  1. \s – any whitespace character

  2. + – match one or more whitespace character

  3. $ – at the end of the string

You can read more from here.

Ankur Lathi
  • 7,636
  • 5
  • 37
  • 49
3

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
2

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 !

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
0

try this regex

    str = str.replaceAll("(.+?) +", "$1");
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

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

   }
}
John Snow
  • 977
  • 7
  • 12
0

In case, if the query was for .net language then you can use the built-in RTRIM method to achieve the same.

MansoorShaikh
  • 913
  • 1
  • 6
  • 19
0

In .NET/C# you can use the TrimEnd method on your string object:

" this is linkedin ".TrimEnd();

Hallvar Helleseth
  • 1,867
  • 15
  • 17
0
public class RegexRemoveEnd {   
    public static String removeTrailingSpaces(String text) {
        return text.replaceAll(" +$", "");
    }
}
Multithreader
  • 878
  • 6
  • 14