从字符串的开头修剪逗号?

时间:2014-08-19 21:44:05

标签: java regex string

我有这个arraylist

  

雅加达,印度尼西亚首都。

     

,东京,日本首都。

     马尼拉,菲律宾首都。

我想删除东京和马尼拉的主要逗号。 我应该如何编写通用代码,以便它可以检测字符串是否由逗号引出并删除它?

预期结果:

  

雅加达,印度尼西亚首都。

     

东京,日本首都。

     

菲律宾首都马尼拉。

非常感谢你的帮助。 :)

5 个答案:

答案 0 :(得分:3)

您可以使用正则表达式执行此操作:

for(int index = 0; index < list.size(); index++) {
    String line = list.get(index);
    if (line != null && line.charAt(0) == ',') {
        line = line.replaceFirst("^,+");
        list.set(index, line); // Replace the string in the list
    }
}

如果您使用的是Java 5 +

,它应该可以正常工作

答案 1 :(得分:2)

尝试这样的事情:

String s = ",Manila, the Capital City of Phillipines.";
if( s.length() > 0 && s.trim().charAt(0) == ',' ) {
    s = s.substring(s.indexOf(',')+1).trim();
}

如果您必须删除许多逗号,请使用while而不是if:

String s = " ,  ,,Manila, the Capital City of Phillipines.";
while( s.length() > 0 && s.trim().charAt(0) == ',' ) {
    s = s.substring(s.indexOf(',')+1).trim();
}

答案 2 :(得分:0)

这个怎么样(它甚至会替换原始列表中的值):

    ArrayList<String> list = new ArrayList<String>(); // This is your ArrayList
    Iterator<String> it = list.iterator(); // Get your list iterator
    while(it.hasNext()){ // do a while loop to manipulate the elements
        String element = it.next(); // Get the next element of your list
        element = element.replaceFirst("^,+"); // Remove the leading comma
        it.set(element); // Replace your changed element in the list
    }

答案 3 :(得分:0)

使用startswith()substring()

String[] strings = {"Jakarta, the Capital City of Indonesia.",
                ",Tokyo, the Capital City of Japan.",
                ",Manila, the Capital City of Phillipines."};
for(String str: strings){
    str = str.startsWith(",") ? str.substring(1) : str;
    System.out.println(str);
}

答案 4 :(得分:0)

for (String st : list)
    while (st.startsWith(","))
        st.subString(1);