PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 5, 2022

[FIXED] How to remove a white space at the end of a string in java?

 September 05, 2022     java, remove-if, spaces, string, trim     No comments   

Issue

I am trying to remove exactly one white space at the end of a string. eg. I want " XXXX " to be " XXXX". The trim() method in java removes all leading and trailing whitespaces.

Any help will be appreciated :)


Solution

If you just want to trim whitespace at the end, use String#replaceAll() with an appropriate regex:

String input = " XXXX ";
String output = input.replaceAll("\\s+$", "");
System.out.println("***" + input + "***");   // *** XXXX ***
System.out.println("***" + output + "***");  // *** XXXX***

If you really want to replace just one whitespace character at the end, then replace on \s$ instead of \s+$.



Answered By - Tim Biegeleisen
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing