从逗号分隔的字符串中删除尾随逗号

时间:2020-12-22 00:20:11

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.

我从具有多个逗号(,)的数据库中获得字符串。我想去掉最后一个逗号,但是我找不到一个简单的方法。

What I have: kushalhs, mayurvm, narendrabz,

我有:kushalhs, mayurvm, narendrabz,

What I want: kushalhs, mayurvm, narendrabz

我想要的是:库沙勒斯、玛雅、纳伦德拉布兹

15 个解决方案

#1


102  

To remove the ", " part which is immediately followed by end of string, you can do:

若要删除“,”部分,该部分后面紧跟着字符串的末尾,您可以这样做:

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

This handles the empty list (empty string) gracefully, as opposed to lastIndexOf / substring solutions which requires special treatment of such case.

这将优雅地处理空列表(空字符串),而不是需要对这种情况进行特殊处理的lastIndexOf / substring解决方案。

Example code:

示例代码:

String str = "kushalhs, mayurvm, narendrabz, ";
str = str.replaceAll(", $", "");
System.out.println(str);  // prints "kushalhs, mayurvm, narendrabz"

NOTE: Since there has been some comments and suggested edits about the ", $" part: The expression should match the trailing part that you want to remove.

注意:由于有一些关于“,$”部分的评论和建议编辑:表达式应该与您想要删除的结尾部分匹配。

  • If your input looks like "a,b,c,", use ",$".
  • 如果您的输入看起来像“a、b、c”、“use”、“$”。
  • If your input looks like "a, b, c, ", use ", $".
  • 如果您的输入看起来像“a、b、c”、“use”、“$”。
  • If your input looks like "a , b , c , ", use " , $".
  • 如果你的输入看起来像“a, b, c,”,使用“,$”。

I think you get the point.

我想你明白了。

#2


9  

You can use this:

您可以使用:

String abc = "kushalhs , mayurvm , narendrabz ,";
String a = abc.substring(0, abc.lastIndexOf(","));

#3


5  

Use Guava to normalize all your commas. Split the string up around the commas, throw out the empties, and connect it all back together. Two calls. No loops. Works the first time:

使用番石榴使所有的逗号正常化。把绳子绕着逗号分开,把空的东西扔出去,把它们连在一起。两个电话。没有循环。第一次工作:

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;

public class TestClass {

    Splitter splitter = Splitter.on(',').omitEmptyStrings().trimResults();
    Joiner joiner = Joiner.on(',').skipNulls();

    public String cleanUpCommas(String string) {
        return joiner.join(splitter.split(string));
    }

}



public class TestMain {

    public static void main(String[] args) {
        TestClass testClass = new TestClass();

        System.out.println(testClass.cleanUpCommas("a,b,c,d,e"));
        System.out.println(testClass.cleanUpCommas("a,b,c,d,e,,,,,"));
        System.out.println(testClass.cleanUpCommas("a,b,,, ,c,d,  ,,e,,,,,"));
        System.out.println(testClass.cleanUpCommas("a,b,c,d,  e,,,,,"));
        System.out.println(testClass.cleanUpCommas(",,, ,,,,a,b,c,d,  e,,,,,"));
    }

}

Output:

输出:

a,b,c,d,e
a,b,c,d,e
a,b,c,d,e
a,b,c,d,e
a,b,c,d,e

a、b、c、d、e a、b、c、d、e a、b、c、d、e a、b、c、d、e a、b、c、d、e

Personally, I hate futzing around with counting limits of substrings and all that nonsense.

就我个人而言,我讨厌对子字符串的计数限制和所有那些胡扯。

#4


3  

For more than one commas

不止一个逗号

            String names = "Hello,World,,,";
    System.out.println(names.replaceAll("(,)*$", ""));

Output: Hello,World

输出:你好,世界

#5


2  

I'm late on this thread but hope it will help to some one.......

我在这条线上迟到了,但希望它能帮助一些人……

String abc = "kushalhs , mayurvm , narendrabz ,";

if(abc.indexOf(",") != -1){
    abc = abc.substring(0,abc.length() - 1);
}

#6


1  

This method is in BalusC's StringUtil class. his blog

这个方法在BalusC的StringUtil类中。他的博客

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, ", ", ");

#7


1  

(^(\s*?\,+)+\s?)|(^\s+)|(\s+$)|((\s*?\,+)+\s?$)

Regexr

Regexr

ex:

例:

a, b, c
, ,a, b, c, 
,a, b, c   ,
,,a, b, c, ,,,
, a, b, c,    ,
    a, b, c     
     a, b, c ,,
, a, b, c, 
, ,a, b, c, ,
 , a, b, c , 
,,, a, b, c,,, 
,,, ,,,a, b, c,,, ,,,
,,, ,,, a, b, c,,, ,,,
 ,,,a, b, c ,,,
 ,,,a, b, c,,, 
   a, b, c   

becomes:

就变成:

a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c

#8


0  

Check if str.charAt(str.length() -1) == ','. Then do str = str.substring(0, str.length()-1)

检查str.charAt(str.length() -1)是否= ','。然后执行str = string .substring(0, string .length()-1)

#9


0  

    String str = "kushalhs , mayurvm , narendrabz ,";
    System.out.println(str.replaceAll(",([^,]*)$", "$1"));

#10


0  

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(", $", "");

#11


0  

public static String removeExtraCommas(String entry) {
    if(entry==null)
        return null;

    String ret="";
    entry=entry.replaceAll("\\s","");
    String arr[]=entry.split(",");
    boolean start=true;
    for(String str:arr) {
        if(!"".equalsIgnoreCase(str)) {
            if(start) {
                ret=str;
                start=false;
            }
            else {
            ret=ret+","+str;
            }
        }
    }               
    return ret;

}

#12


0  

You can do something like using join function of String class.

可以使用String类的join函数。

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);
    }

}

#13


0  

i am sharing code form my project using regular expression you can do this...

我正在使用正则表达式共享我的项目中的代码。

String ChildBelowList = "";

    if (!Childbelow.isEmpty()) {
        for (int iCB = 0; iCB < Childbelow.size(); iCB++) {

            ChildBelowList = ChildBelowList += Childbelow.get(iCB) + ",";



        }
        ChildBelowList = ChildBelowList.replaceAll("(^(\\s*?\\,+)+\\s?)|(^\\s+)|(\\s+$)|((\\s*?\\,+)+\\s?$)", "");

        tv_childbelow.setText(ChildBelowList);

    } else {
        ll_childbelow.setVisibility(View.GONE);
    }

#14


-1  

You can do something like this using 'Java 8'

您可以使用“Java 8”执行类似的操作

private static void appendNamesWithComma() {
    List<String> namesList = Arrays.asList("test1", "tester2", "testers3", "t4");
    System.out.println(namesList.stream()
                                .collect(Collectors.joining(", ")));

}

#15


-1  

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;
    }

#1


102  

To remove the ", " part which is immediately followed by end of string, you can do:

若要删除“,”部分,该部分后面紧跟着字符串的末尾,您可以这样做:

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

This handles the empty list (empty string) gracefully, as opposed to lastIndexOf / substring solutions which requires special treatment of such case.

这将优雅地处理空列表(空字符串),而不是需要对这种情况进行特殊处理的lastIndexOf / substring解决方案。

Example code:

示例代码:

String str = "kushalhs, mayurvm, narendrabz, ";
str = str.replaceAll(", $", "");
System.out.println(str);  // prints "kushalhs, mayurvm, narendrabz"

NOTE: Since there has been some comments and suggested edits about the ", $" part: The expression should match the trailing part that you want to remove.

注意:由于有一些关于“,$”部分的评论和建议编辑:表达式应该与您想要删除的结尾部分匹配。

  • If your input looks like "a,b,c,", use ",$".
  • 如果您的输入看起来像“a、b、c”、“use”、“$”。
  • If your input looks like "a, b, c, ", use ", $".
  • 如果您的输入看起来像“a、b、c”、“use”、“$”。
  • If your input looks like "a , b , c , ", use " , $".
  • 如果你的输入看起来像“a, b, c,”,使用“,$”。

I think you get the point.

我想你明白了。

#2


9  

You can use this:

您可以使用:

String abc = "kushalhs , mayurvm , narendrabz ,";
String a = abc.substring(0, abc.lastIndexOf(","));

#3


5  

Use Guava to normalize all your commas. Split the string up around the commas, throw out the empties, and connect it all back together. Two calls. No loops. Works the first time:

使用番石榴使所有的逗号正常化。把绳子绕着逗号分开,把空的东西扔出去,把它们连在一起。两个电话。没有循环。第一次工作:

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;

public class TestClass {

    Splitter splitter = Splitter.on(',').omitEmptyStrings().trimResults();
    Joiner joiner = Joiner.on(',').skipNulls();

    public String cleanUpCommas(String string) {
        return joiner.join(splitter.split(string));
    }

}



public class TestMain {

    public static void main(String[] args) {
        TestClass testClass = new TestClass();

        System.out.println(testClass.cleanUpCommas("a,b,c,d,e"));
        System.out.println(testClass.cleanUpCommas("a,b,c,d,e,,,,,"));
        System.out.println(testClass.cleanUpCommas("a,b,,, ,c,d,  ,,e,,,,,"));
        System.out.println(testClass.cleanUpCommas("a,b,c,d,  e,,,,,"));
        System.out.println(testClass.cleanUpCommas(",,, ,,,,a,b,c,d,  e,,,,,"));
    }

}

Output:

输出:

a,b,c,d,e
a,b,c,d,e
a,b,c,d,e
a,b,c,d,e
a,b,c,d,e

a、b、c、d、e a、b、c、d、e a、b、c、d、e a、b、c、d、e a、b、c、d、e

Personally, I hate futzing around with counting limits of substrings and all that nonsense.

就我个人而言,我讨厌对子字符串的计数限制和所有那些胡扯。

#4


3  

For more than one commas

不止一个逗号

            String names = "Hello,World,,,";
    System.out.println(names.replaceAll("(,)*$", ""));

Output: Hello,World

输出:你好,世界

#5


2  

I'm late on this thread but hope it will help to some one.......

我在这条线上迟到了,但希望它能帮助一些人……

String abc = "kushalhs , mayurvm , narendrabz ,";

if(abc.indexOf(",") != -1){
    abc = abc.substring(0,abc.length() - 1);
}

#6


1  

This method is in BalusC's StringUtil class. his blog

这个方法在BalusC的StringUtil类中。他的博客

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, ", ", ");

#7


1  

(^(\s*?\,+)+\s?)|(^\s+)|(\s+$)|((\s*?\,+)+\s?$)

Regexr

Regexr

ex:

例:

a, b, c
, ,a, b, c, 
,a, b, c   ,
,,a, b, c, ,,,
, a, b, c,    ,
    a, b, c     
     a, b, c ,,
, a, b, c, 
, ,a, b, c, ,
 , a, b, c , 
,,, a, b, c,,, 
,,, ,,,a, b, c,,, ,,,
,,, ,,, a, b, c,,, ,,,
 ,,,a, b, c ,,,
 ,,,a, b, c,,, 
   a, b, c   

becomes:

就变成:

a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c

#8


0  

Check if str.charAt(str.length() -1) == ','. Then do str = str.substring(0, str.length()-1)

检查str.charAt(str.length() -1)是否= ','。然后执行str = string .substring(0, string .length()-1)

#9


0  

    String str = "kushalhs , mayurvm , narendrabz ,";
    System.out.println(str.replaceAll(",([^,]*)$", "$1"));

#10


0  

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(", $", "");

#11


0  

public static String removeExtraCommas(String entry) {
    if(entry==null)
        return null;

    String ret="";
    entry=entry.replaceAll("\\s","");
    String arr[]=entry.split(",");
    boolean start=true;
    for(String str:arr) {
        if(!"".equalsIgnoreCase(str)) {
            if(start) {
                ret=str;
                start=false;
            }
            else {
            ret=ret+","+str;
            }
        }
    }               
    return ret;

}

#12


0  

You can do something like using join function of String class.

可以使用String类的join函数。

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);
    }

}

#13


0  

i am sharing code form my project using regular expression you can do this...

我正在使用正则表达式共享我的项目中的代码。

String ChildBelowList = "";

    if (!Childbelow.isEmpty()) {
        for (int iCB = 0; iCB < Childbelow.size(); iCB++) {

            ChildBelowList = ChildBelowList += Childbelow.get(iCB) + ",";



        }
        ChildBelowList = ChildBelowList.replaceAll("(^(\\s*?\\,+)+\\s?)|(^\\s+)|(\\s+$)|((\\s*?\\,+)+\\s?$)", "");

        tv_childbelow.setText(ChildBelowList);

    } else {
        ll_childbelow.setVisibility(View.GONE);
    }

#14


-1  

You can do something like this using 'Java 8'

您可以使用“Java 8”执行类似的操作

private static void appendNamesWithComma() {
    List<String> namesList = Arrays.asList("test1", "tester2", "testers3", "t4");
    System.out.println(namesList.stream()
                                .collect(Collectors.joining(", ")));

}

#15


-1  

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;
    }