-2

My problem is to replace only the last occurrence of a character in the string with another character. When I used the String.replace(char1, char2), it replaces all the occurrences of the character in the string.

For example, I have an address string like

String str = "Addressline1,Addressline2,City,State,Country,";.

I need to replace the occurrence of ',' at the end of the string with '.'.

My code to replace the character is

str = str.replace(str.charAt(str.lastIndexOf(",")),'.');

After replacing, the string looks like:

Addressline1.Addressline2.City.State.Country.

Is there the problem in Java SDK?. If yes, how to resolve it?

Jon Ball
  • 3,032
  • 3
  • 23
  • 24
Madhan
  • 555
  • 5
  • 23
  • 1
    No, `#replace` takes a character argument and replaces it with the second. You've effectively said "find the character at the place where the character is `,`, and then replace all of those characters with `.`" – Rogue Oct 18 '16 at 04:46
  • try this. – D.J Oct 18 '16 at 04:46
  • There seems to be some confusion over what you want. Do you want to (1) replace the last character of the string with `.`, no matter what it is; (2) replace the last character of the string with `.` only if it's a comma; or (3) replace the last _comma_ in the string with `.` even if there are characters following the comma? – ajb Oct 18 '16 at 05:05
  • @suku, I need a solution for this problem in java not in javascript. – Madhan Oct 18 '16 at 06:55

2 Answers2

3

You should use String.replaceAll which use regex

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

The $ mean the end of the String

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • I don't think this is right. Looking at what the OP is trying to do, I think he's trying to replace the last comma in the string, _even if the comma is not the last character of the string_. Your code doesn't do that. On the other hand, he just approved your answer while I was typing this comment, so maybe it really is what he wants. – ajb Oct 18 '16 at 05:03
  • @ajb `I need to replace the occurrence of ',' at the end of the string with '.'.` – Scary Wombat Oct 18 '16 at 05:04
  • OK, I see that the OP sort of contradicted himself. – ajb Oct 18 '16 at 05:07
-1

The Java replace function has a method declaration of:

public String replace(char oldChar, char newChar)

According to the docs replace will:

Return a new string resulting from replacing all occurrences of oldChar in this string with newChar.

So your code:

str.charAt(str.lastIndexOf(","))

Will clearly return the character ,. replace will then replace all instances of the oldChar , with the newChar .. This explains the behavior you were seeing.

The solution that @ScaryWombat beat me to is your best option:

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

Since, in regular expression terms, $ denotes the end of a String.

Hope this helps!

James Taylor
  • 6,158
  • 8
  • 48
  • 74