Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Whitespaces ONLY at the end of a String (java) [duplicate]

i already found similar topics but they were not really helpful.

I basically need to know how I can remove whitespaces ONLY at the end of a string.

For example: String a = "Good Morning it is a nice day ";

Should be: String a = "Good Morning it is a nice day";

You see there are like three whitespaces at the end or something. I got replaceAll() as a suggestion but as I said I only want to remove the remaining whitespaces at the end. How do I do that ? I already tried different things like going through the String like this:

for(int i = a.length(); i > a.length() - 3; i++){
     if(a.charAt(i) == ' '){
           <insert Solution here>
     }
}

With the code above I wanted to check the last three Chars of the string because it is sufficient. It is sufficient for the stuff I want to do. There wont be a case with 99+ whitespaces at the end (probably).

But as you see I still dont know which method to use or if this is actually the right way.

Any suggestions please ?

like image 571
J.Doe Avatar asked Oct 24 '25 17:10

J.Doe


2 Answers

If your goal is to cut only the trailing white space characters and to save leading white space characters of your String, you can use String class' replaceFirst() method:

String yourString = "   my text. ";
String cutTrailingWhiteSpaceCharacters = yourString.replaceFirst("\\s++$", "");

\\s++ - one or more white space characters (use of possesive quantifiers (take a look at Pattern class in the Java API documentation, you have listed all of the special characters used in regułar expressions there)),

$ - end of string

You might also want to take a look at part of my answer before the edit:

If you don't care about the leading white space characters of your input String: String class provides a trim() method. It might be quick solution in your case as it cuts leading and trailing whitespaces of the given String.

like image 107
Przemysław Moskal Avatar answered Oct 26 '25 08:10

Przemysław Moskal


You can either use the regular expression:

a = a.replaceAll("\\s+$", "");

to remove trailing whitespaces and store the result back into a

or using a for loop:

String a = "Good Morning it is a nice day    ";
StringBuilder temp = new StringBuilder(a);
for( int i = temp.length() - 1 ; i >= 0; i--){
     if(temp.charAt(i) == ' '){
          temp.deleteCharAt(i);
     }else{
          break;
     }
}

a = temp.toString();
like image 23
Ousmane D. Avatar answered Oct 26 '25 07:10

Ousmane D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!