Here you can find the source of reverseCommaDelimitedString(final String string)
Parameter | Description |
---|---|
string | the given string |
public static String reverseCommaDelimitedString(final String string)
//package com.java2s; /*/*from w w w . ja v a2 s . co m*/ * StringUtils.java * * Created on October 4, 2006, 2:36 PM * * Description: * * Copyright (C) 2006 Stephen L. Reed. * * This program is free software; you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; * if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ import java.util.ArrayList; import java.util.List; public class Main { /** Reverses a string which consists of comma-separated items. * "a, b, c" --> "c, b, a" * * @param string the given string * @return the string with the comma-separated items reversed */ public static String reverseCommaDelimitedString(final String string) { final List<String> items = new ArrayList<>(); final int string_len = string.length(); int index = 0; for (int i = 0; i < string_len; i++) { final char ch = string.charAt(i); if (ch == ',') { if (i > index) { items.add(string.substring(index, i).trim()); } index = i + 1; } } if (index < string_len) { items.add(string.substring(index).trim()); } final StringBuilder stringBuilder = new StringBuilder(); boolean isFirst = true; for (int i = items.size() - 1; i >= 0; i--) { if (isFirst) { isFirst = false; } else { stringBuilder.append(", "); } stringBuilder.append(items.get(i)); } return stringBuilder.toString(); } }