繁体   English   中英

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

[英]Remove trailing comma from comma-separated string

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

我所拥有的: kushalhs, mayurvm, narendrabz,

我想要什么: kushalhs, mayurvm, narendrabz

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

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 , " ,请使用" , $"

我认为你说对了。

你可以使用这个:

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

使用 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

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

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

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

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

多于一个逗号

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

输出:你好,世界

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

正则表达式

前任:

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

还有一个……这也清除了与空格混合的内部逗号:

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

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

您可以执行类似使用 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);
    }

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

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

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

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

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

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

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

或者你也可以试试这个:

string = string.replaceAll(", $", "");
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;

}

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

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

你可以使用“Java 8”来做这样的事情

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

}

或者像这样:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM