42

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

13 Answers 13

75

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

Sign up to request clarification or add additional context in comments.

4 Comments

notice in javascript length() is length with out brackets
@danihp and in c# it's .Length...but then I'd expect a completely unrelated language to have different code javascriptisnotjava.io
@weston, sure!! Let explain my self. I found and applied Abubakkar Rangara's solution searching about javascript issue. Because this, I wrote comment (and also I vote it up), to other users than found this answer looking for a jscript snipped. Snipped runs on both, java and javascript just with the little change. Finally, a quote from Big Data Borat just for laugh: twitter.com/bigdataborat/status/356928145041002498
@danihp That's a good one, I added to that site. Congrats to you too!
17

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

Comments

13

To get the required result you can do following:

fieldName = fieldName.trim();
fieldName = fieldName.substring(0,fieldName.length() - 1);

1 Comment

It will work but in case null value in string it will run time error, better to check if not null value then should execute the code !!!
11
fieldName = fieldName.substring(0, string.length()-1) + " ";

Comments

10

Firstly Strings are immutable in java, you have to assign the result of the replace to a variable.

fieldName = fieldName.replace("watever","");

You can use also use regex as an option using String#replaceAll(regex, str);

fieldName = fieldName.replaceAll(",$","");

1 Comment

second solution is good for stream pipe ...
7

Try this:

s = s.replaceAll("[,]$", "");

2 Comments

I guess this will replace all ","
@TaritRay It won't, because the dollar sign in the regular expression represents the end of the string. So s = s.replaceAll("[,]", ""); would remove all commas, while panticz.de's example will only replace a comma at the end of the string.
3
    if (fieldName.endsWith(",")) {
        fieldName = fieldName.substring(0, fieldName.length()-1) + " ";
    }

Comments

2

StringBuilder replace method can be used to replace the last character.

StringBuilder.replace(startPosition, endPosition, newString)

StringBuilder builder = new StringBuilder(fieldName);
builder.replace(builder.length()-1, builder.length(), "");
builder.toString();

Comments

2

You can simply use :

if(fieldName.endsWith(","))
{
   StringUtils.chop(fieldName);
}

from commons-lang

Comments

2

org.apache.commons.lang3.StringUtils.removeEnd() and org.springframework.util.StringUtils.trimTrailingCharacter() are your friends:

StringUtils.removeEnd(null, *)      = null
StringUtils.removeEnd("", *)        = ""
StringUtils.removeEnd(*, null)      = *
StringUtils.removeEnd("www.domain.com", ".com.")  = "www.domain.com"
StringUtils.removeEnd("www.domain.com", ".com")   = "www.domain"
StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
StringUtils.removeEnd("abc", "")    = "abc"
    @Test
    public void springStringUtils() {
        String url = "https://some.site/path/";

        String result = org.springframework.util.StringUtils.trimTrailingCharacter(url, '/');

        assertThat(result, equalTo("https://some.site/path"));
    }

Comments

1

you can use regular expressions to identify the last comma (,) and replace it with " " as follow:

if(fieldName.endsWith(","))
{                           
fieldName = fieldName.replace(/,([^,]*)$/," ");
}

1 Comment

Though perfectly correct, your answer is JavaScript. This topic is Java-related.
0

Already @Abubakkar Rangara answered easy way to handle your problem

Alternative is :

String[] result = null;
if(fieldName.endsWith(",")) {                           
String[] result = fieldName.split(",");
    for(int i = 1; i < result.length - 1; i++) {
        result[0] = result[0].concat(result[i]);
    }
}

Comments

-6

Modify the code as fieldName = fieldName.replace("," , " ");

2 Comments

That will replace all occurrences of "," with " ", but they only want the last one to be replaced.
Do not provide wrong solutions if you can not read/understand question clearly

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.