如何有效地替换一个或多个字符

时间:2014-06-21 06:57:08

标签: android string replace

我有一个用逗号分隔的字符串,如下所示

  

1,2,4,6,8,11,14,15,16,17,18

此字符串是在用户输入时生成的。假设用户想要删除任何数字,我必须重建没有指定数字的字符串。

如果当前字符串是:

  

1,2,4,6,8,11,14,15,16,17,18

用户意图删除1,最后一个字符串必须是:

  

2,4,6,8,11,14,15,16,17,18

我尝试使用以下代码实现此目的:

 //String num will be the number to be removed
 old = tv.getText().toString(); //old string
 newString = old.replace(num+",",""); //will be the new string

这可能有时会起作用但是我确定它不会对我已经显示的上述示例起作用,如果我尝试删除1,它也会删除{{1}的最后一部分因为还存在11

4 个答案:

答案 0 :(得分:2)

你可以使用它。这是我能想到的最简单的方法:

//String num will be the number to be removed
 old=","+tv.getText().toString()+",";//old string commas added to remove trailing entries
 newString=old.replace(","+num+",",",");// will be the new string
 newString=newString.substring(1,newString.length()-1); // removing the extra commas added

这适用于您想要做的事情。我在字符串的开头和结尾添加了逗号,这样您也可以删除第一个和最后一个条目。

答案 1 :(得分:1)

您可以先split字符串,然后检查附加这些值的数字,该数字不等同于将被删除的数字;

<强>样品:

 String formated = "1,2,4,6,8,11,14,15,16,17,18";
    String []s = formated.split(",");
    StringBuilder newS = new StringBuilder();
    for(String s2 : s)
    {
        if(!s2.equals("1"))
            newS.append(s2 + ",");
    }
    if(newS.length() >= 1)
        newS.deleteCharAt(newS.length() - 1);
    System.out.println(newS);

<强>结果:

2,4,6,8,11,14,15,16,17,18

答案 2 :(得分:0)

static public String removeItemFromCommaDelimitedString(String str, String item)
{
    StringBuilder builder = new StringBuilder();
    int count = 0;

    String [] splits = str.split(",");

    for (String s : splits)
    {
        if (item.equals(s) == false)
        {
            if (count != 0)
            {
                builder.append(',');
            }
            builder.append(s);
            count++;
        }
    }
    return builder.toString();
}

答案 3 :(得分:0)

     String old = "1,2,4,6,8,11,14,15,16,17,18";
     int num = 11;
     String toRemove = "," + num + "," ;
     String oldString = "," + old + ",";
     int index = oldString.indexOf(toRemove);
     System.out.println(index);
     String newString = null;
     if(index > old.length() - toRemove.length() + 1){
        newString = old.substring(0, index - 1);
     }else{
         newString = old.substring(0, index) + old.substring(index + toRemove.length()    -1 , old.length());
     }
     System.out.println(newString);