I have a string:
String fieldName = "A=2,B=3 and C=3,";
Now I want to replace last ,
with space.
I have used:
if (fieldName.endsWith(",")) { fieldName.replace(",", " "); fieldName = fieldName.replace((char) (fieldName.length() - 1), 'r'); } System.out.println("fieldName = " + fieldName);
But still I am getting the same old string. How I can get this output instead?
fieldName = A=2,B=3 and C=3
replace((char) (fieldName. length() - 1), 'r'); } System. out. println("fieldName = " + fieldName);
Use the String. replace() method to replace the last character in a string, e.g. const replaced = str. replace(/. $/, 'replacement'); .
You can simply use substring
:
if(fieldName.endsWith(",")) { fieldName = fieldName.substring(0,fieldName.length() - 1); }
Make sure to reassign your field after performing substring
as Strings are immutable in java
i want to replace last ',' with space
if (fieldName.endsWith(",")) { fieldName = fieldName.substring(0, fieldName.length() - 1) + " "; }
If you want to remove the trailing comma, simply get rid of the + " "
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With