-3

Is there any inbuilt method for trimming only trailing white spaces from a string? that is similar to rtrim available in other languages

Example: String str1 = "stackoverflow "; String str2 = " stackoverflow ";

should become,

str1 = "stackoverflow"; str2 = " stackoverflow";

FirmView
  • 3,130
  • 8
  • 34
  • 50

4 Answers4

3

String has method called trim();

str1.trim(); will do the job for you.

Update:

If you don't want to trim() leading spaces, you may need to write your own implementation as DNA suggested.

kosa
  • 65,990
  • 13
  • 130
  • 167
3

How about checking the source code for String.trim() and modifying it?

Disabling the whitespace removal at the start or the end is a matter of commenting out one line...

DNA
  • 42,007
  • 12
  • 107
  • 146
1

You can either use a regex or iterate over the string to remove whitespace characters.

Either way, you should read the documentation here: Java String

jahroy
  • 22,322
  • 9
  • 59
  • 108
0

Plenty of ways to do this, regex being one of them:

To remove trailing whitespaces:

s/\s+$//

Somewhat related, but probably not what you're looking for, to remove leading whitespaces:

s/^\s+//

PS: I believe you mean to say trailing whitespaces, as leading whitespaces imply that the whitespaces come first.

Jarmund
  • 3,003
  • 4
  • 22
  • 45