1

Hi I have a string in java that goes like this:

"742706t000gf4604008264468468400000000000000000000000"

How would I remove all the trailing 0's at the end but leaving the ones in between?

Thanks!

1
  • 2
    value.replaceAll("0+$", ""); or with commons-lang. Commented Jan 4, 2015 at 11:54

1 Answer 1

5

You can use a regex with the "$" character that indicates string's end, and the String.replaceAll() method

str = str.replaceAll("0+$", "")
Sign up to request clarification or add additional context in comments.

8 Comments

That doesn't seem to work. The 0's are still there. It is a hexString formed from a byte array.
@Shiv Strings are immutable. str = str.replaceAll("0+$", ""); works for me.
@Shiv what @ZouZou means is you should reassign the result of str.replaceAll("0+$", "") to a variable - it creates a NEW string without the zeros, and it does NOT modify the old string
Well it is a hex binary string made from a byte array. Does it make a difference?
That's what I did. String hexReply2 = hexReply1.replaceAll("0+$", "");
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.