Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing last character in a String with java

Tags:

java

string

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 
like image 247
user1697114 Avatar asked Mar 07 '13 10:03

user1697114


People also ask

How do you replace last character of a string in Java?

replace((char) (fieldName. length() - 1), 'r'); } System. out. println("fieldName = " + fieldName);

How do I change the last character of a string?

Use the String. replace() method to replace the last character in a string, e.g. const replaced = str. replace(/. $/, 'replacement'); .


2 Answers

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

like image 165
Abubakkar Avatar answered Oct 20 '22 10:10

Abubakkar


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 + " ".

like image 44
NPE Avatar answered Oct 20 '22 10:10

NPE