Sally Trivone
Sally Trivone

Reputation: 35

how to remove every other comma from a string

In the list below how would you remove every other comma to produce.

("a,1.50,b,2.00,c,2.50") -> ("a 1.50, b 2.00, c 2.50")

I tried using a delimiter, but am unsure how to use it in this instance.

public void listItems() {

    if(drinksVender!=null)
    { 
        Scanner noCommaList = new Scanner(drinksVender).useDelimiter("[,]");
        String[] listItem = drinksVender.split(",");

    for(int numOfDrinks = 0; numOfDrinks < listItem.length; numOfDrinks++)
        {   

        System.out.println("[" +(numOfDrinks) + "] " + listItem[numOfDrinks] );

        }
    }

Upvotes: 1

Views: 163

Answers (1)

emsimpson92
emsimpson92

Reputation: 1778

You can use regular expressions for this. You'll want to use

myString.replaceAll("(?<=[a-zA-Z]),(?=\d)", " ");

Demo

Upvotes: 2

Related Questions