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

时间:2011-10-18 11:47:59

标签: java string

我从数据库中获得了多个逗号(,)的字符串。我想删除最后一个逗号,但我真的找不到一种简单的方法。

我拥有的内容:kushalhs, mayurvm, narendrabz,

我想要的是什么:kushalhs, mayurvm, narendrabz

17 个答案:

答案 0 :(得分:117)

要删除紧跟字符串结尾的", "部分,您可以执行以下操作:

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

这会优雅地处理空列表(空字符串),而不是需要特殊处理此类案例的lastIndexOf / substring解决方案。

示例代码:

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

注意:由于对", $"部分有一些评论和建议的修改:表达式应与您要删除的结尾部分相匹配。

  • 如果您的输入看起来像"a,b,c,",请使用",$"
  • 如果您的输入看起来像"a, b, c, ",请使用", $"
  • 如果您的输入看起来像"a , b , c , ",请使用" , $"

我认为你明白了。

答案 1 :(得分:9)

您可以使用:

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

答案 2 :(得分:7)

使用Guava标准化所有逗号。将字符串分成逗号,围绕逗号,然后将它们全部连接在一起。两个电话。没有循环。第一次工作:

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

}

输出:

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

就个人而言,我讨厌计算子串的限制和所有废话。

答案 3 :(得分:3)

对于多个逗号

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

输出: 你好,世界

答案 4 :(得分:2)

我在这个帖子上迟到了,但希望它对某个人有所帮助.......

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

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

答案 5 :(得分:1)

此方法位于BalusC的StringUtil类中。 his blog

我经常使用它并修剪任何值的任何字符串:

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

例如:

trim("1, 2, 3, ", ", ");

答案 6 :(得分:1)

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

Regexr

例如:

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   

变为:

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

答案 7 :(得分:1)

您可以执行类似String类的连接功能的操作。

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

}

答案 8 :(得分:0)

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

答案 9 :(得分:0)

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

答案 10 :(得分:0)

你可以试试这个,它对我有用:

if (names.endsWith(",")) {
    names = names.substring(0, names.length() - 1);
}

或者你也可以试试这个:

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)

还有一个...这也可以清除内部逗号和空格:

, , , ,one,,, , ,two three, , , ,,four, , , , ,one,two three, four

text.replaceAll("^(,|\\s)*|(,|\\s)*$", "").replaceAll("(\\,\\s*)+", ",");

答案 13 :(得分:0)

我正在使用正则表达式在我的项目中共享代码,你可以这样做......

func isSearching() -> Bool {
  return searchController.isActive && !searchBarIsEmpty()
}

func searchBarIsEmpty() -> Bool {
  // Returns true if the text is empty or nil
  return searchController.searchBar.text?.isEmpty ?? true
}

答案 14 :(得分:-1)

package com.app;

public class SiftNumberAndEvenNumber {

    public static void main(String[] args) {

        int arr[] = {1,2,3,4,5};
        int arr1[] = new int[arr.length];
        int shiftAmount=3;
        
        for(int i = 0; i < arr.length; i++){
            int newLocation = (i + (arr.length - shiftAmount)) % arr.length;
            arr1[newLocation] = arr[i];
            
        }
        for(int i=0;i<arr1.length;i++) {
            if(i==arr1.length-1) {
                System.out.print(arr1[i]);
            }else {
                System.out.print(arr1[i]+",");
            }
        }
        System.out.println();
        for(int i=0;i<arr1.length;i++) {
            if(arr1[i]%2==0) {
                System.out.print(arr1[i]+" ");
            }
        }
    }
}

答案 15 :(得分:-1)

或类似的东西:

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

答案 16 :(得分:-1)

你可以使用'Java 8'

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

}