I got String from the database which have multiple commas (,
) . I want to remove the last comma but I can\'t really find a simple way of doing it.
You can do something like using join function of String class.
import java.util.Arrays;
import java.util.List;
public class Demo {
public static void main(String[] args) {
List<String> items = Arrays.asList("Java", "Ruby", "Python", "C++");
String output = String.join(",", items);
System.out.println(output);
}
}
This method is in BalusC's StringUtil class. his blog
i use it very often and will trim any string of any value:
/**
* Trim the given string with the given trim value.
* @param string The string to be trimmed.
* @param trim The value to trim the given string off.
* @return The trimmed string.
*/
public static String trim(String string, String trim) {
if (string == null) {
return null;
}
if (trim.length() == 0) {
return string;
}
int start = 0;
int end = string.length();
int length = trim.length();
while (start + length <= end && string.substring(
start, start + length).equals(trim)) {
start += length;
}
while (start + length <= end && string.substring(
end - length, end).equals(trim)) {
end -= length;
}
return string.substring(start, end);
}
ex:
trim("1, 2, 3, ", ", ");
Or something like this:
private static String myRemComa(String input) {
String[] exploded = input.split(",");
input="";
boolean start = true;
for(String str : exploded) {
str=str.trim();
if (str.length()>0) {
if (start) {
input = str;
start = false;
} else {
input = input + "," + str;
}
}
}
return input;
}
You can try with this, it worked for me:
if (names.endsWith(",")) {
names = names.substring(0, names.length() - 1);
}
Or you can try with this too:
string = string.replaceAll(", $", "");