2

I have an output like

1054273,
1148244,
1174481,
1175759,
1180656,
1181151,

I need to remove the comma at the end.

I tried the code :

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

But the output shows like all the commas were removed.

Can anyone help me to solve this??

Thanks, SK

Lake
  • 4,072
  • 26
  • 36
Sudeep Krishna
  • 69
  • 1
  • 1
  • 8
  • Possible duplicate of [Java - Trim leading or trailing characters from a string?](https://stackoverflow.com/questions/25691415/java-trim-leading-or-trailing-characters-from-a-string) – Century Feb 28 '18 at 10:05
  • you can use split with (",") and create your output as you want – Azzabi Haythem Feb 28 '18 at 10:18

4 Answers4

2
String text = "1054273, 1148244, 1174481, 1175759, 1180656, 1181151,".trim();

if(text.endsWith(","))
   text = text.substring(0, text.lastIndexOf(","))

The original text is trimmed to ensure that you don't have trailing space. Assuming you have a valid-length string.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • What if the comma at the end is not there, you're method will remove another comma that is not supposed to be removed – Century Feb 28 '18 at 10:10
  • @Century The question doesn't ask that. There are **many** other reasons to check whether the string this code is run on ends with a comma. So it should be OK to assume that. – ernest_k Feb 28 '18 at 10:17
  • the question asks to remove the trailing comma, but it doesn't say it is guaranteed to be there (the example given is just an example), therefore you cannot make this assumption. – Century Feb 28 '18 at 10:22
  • @Century don't know whether you convinced me, but you at least persuaded me. Added an `if`. – ernest_k Feb 28 '18 at 10:30
0

If you want to remove a character, why are you replacing it?

Say that you want to remove the last character, because, in fact, the comma is at the end (and I guess it will always be):

str = str.substring(0, str.length() - 1);
aPugLife
  • 989
  • 2
  • 14
  • 25
0

you can use substring like this

  String str = "1054273, 1148244, 1174481, 1175759, 1180656, 1181151,";
            String output = str.substring(0, str.length()-1);
            System.out.println(output);

output is :

1054273, 1148244, 1174481, 1175759, 1180656, 1181151

or if you want to create a custom output you'd better use split and create an array of string like this :

String[] outputArrays = str.split(",");
        Arrays.asList(outputArrays).stream().forEach(System.out::println);

output is (and you free to change it):

 1054273
 1148244
 1174481
 1175759
 1180656
 1181151 
Azzabi Haythem
  • 2,318
  • 7
  • 26
  • 32
0

In your case you can simply remove the last char.

With substring :

str = str.substring(0, str.length() - 1);

With regex :

str = str.replaceAll(".$", "");
veben
  • 19,637
  • 14
  • 60
  • 80