0

I have String like this:

String strCustom1 = "Red, Green, Blue";

I have tried this, but replacing all the , with and

    strCustom = "Red, Green, Blue";
    strCustom = strCustom.replaceAll(",",  " and");

    [or]

    strCustom = strCustom.replace(",",  " and");

Like this:

    Red and Blue and Green

But I just want to replace last , with space+and

So it should look this:

    Red, Green and Blue

In a same way, want to format this:

    String strCustom2 = "Red, Green, Blue, Yellow";

and as a result i want to get this:

    Red, Green, Blue and Yellow
Oreo
  • 2,586
  • 8
  • 38
  • 63

3 Answers3

2

You can do something like this:

strCustom = strCustom.substring(0, strCustom.lastIndexOf(",")) + " and" + strCustom.substring(strCustom.lastIndexOf(",") + 1);
Titus
  • 22,031
  • 1
  • 23
  • 33
  • thank you so much, it works :) i ticked as useful and will share after 9 mins and can you brief me use of strCustom.substring(strCustom.lastIndexOf(",") + 1); – Oreo Sep 02 '15 at 04:56
  • 1
    @Oreo The `substring(int index)` will create a `String` that starts from `index` and ends at the original `String` end. In this example I've included `+ 1` so that the substring start after the last `,` character. – Titus Sep 02 '15 at 05:00
  • 1
    P1. Better to store `strCustom.lastIndexOf(",")` in `int` instead of calling it twice. – akash Sep 02 '15 at 05:05
1

You can try something like this..

String strCustom = "Red, Green, Blue";
StringBuilder sb=new StringBuilder(strCustom);
sb.replace(strCustom.lastIndexOf(","),strCustom.lastIndexOf(",")+1," and");
System.out.println(sb.toString());

Out put:

Red, Green and Blue
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
1

A quick regex will do it for you :

    public static void main(String arf[]) {
        String strCustom1 = "Red, Green, Blue";
        System.out.println(strCustom1.replaceAll(",(?=\\s\\w+$)"," and" )); // find the last ",".
    }

O/P:

Red, Green and Blue
TheLostMind
  • 35,966
  • 12
  • 68
  • 104