【问题标题】:Deleting a word in a String/String Array删除字符串/字符串数组中的单词
【发布时间】:2014-12-16 07:38:03
【问题描述】:

因此,如果您要添加字符串,则可以通过+= 方法(我知道并使用atm 的方法)添加它们。但是如何删除字符串/字符串数组中的单词呢?

例子:我有一个字符串

String="Monday,Tuesday,Wednesday"

你是怎么做到的

String="Monday,Wednesday"

请帮忙?

【问题讨论】:

  • 你试过str.replace吗? "星期一、星期二、星期三".replace(",星期二", "")

标签: android


【解决方案1】:

您可以使用replace 方法。

String sentence = "Monday,Tuesday,Wednesday";
String replaced = sentence.replace("Tuesday,", "");

【讨论】:

  • 所以 .replace 中的“Tuesday”是我要替换/删除的单词,而空字符串是“delete”?
  • 是的,如文档中所述。第一个参数是目标(要替换的序列),第二个参数是替换(在你的情况下它只是一个空字符串“”)。
  • 如果字符串只是 "Monday,Tuesday" 那么这将失败。
  • 失败是因为“Monday,Tuesday”不包含“Tuesday”!在发布之前,您应该尝试思考和理解。句末没有逗号“,”。
【解决方案2】:

很简单

只需使用

          yourString = yourString.replaceAll("the text to replace", "");  //the second "" show empty string so the text will get replace by empty string

最后 yourString 将包含你想要的文本 就是这样:)

【讨论】:

  • 我很确定他不是在寻找替换特定单词的方法,而是在寻找单词的索引。但这只是我……
【解决方案3】:

如果你想删除 "Tuesday" 而不是第二个元素,你可以使用 "public String replace(char oldChar, char newChar)" 方法

https://stackoverflow.com/questions/16702357/how-to-replace-a-substring-of-a-string

【讨论】:

    【解决方案4】:

    我想,为了简单起见,我会使用它,否则请转到其他建议的答案...

    使用 Arraylist 存储天数:

    ArrayList<String> days = new ArrayList<String>();
    days.add("Monday");
    days.add("Tuesday");
    days.add("Wednesday");        
    

    用它来创建天字符串:

            public String getDays() {
    
                String daysString = "";
    
                for (int i = 0; i < days.size(); i++) {
                    if (i != 0)
                        daysString += ", ";
                    daysString += days.get(i);
                }
    
                return daysString;
            }
    

    无论何时你想删除使用

    days.remove(1); 
    

    days.remove("Tuesday");
    

    然后再拨打getDays();

    IInd 方法如果你只想使用字符串:

    String list = "Monday,Tuesday,Wednesday";
    System.out.println("New String : " + removeAtIndex(list, 1));
    

    public String removeAtIndex(String string, int index) {
            int currentPointer = 0;
            int lastPointer = string.indexOf(",");
            while (index != 0) {
                currentPointer = string.indexOf(',', currentPointer) + 1;
                lastPointer = string.indexOf(',', lastPointer + 1);
                index--;
            }
    
            String subString = string.substring(currentPointer,
                    lastPointer == -1 ? string.length() : lastPointer);
    
            return string.replace((currentPointer != 0 ? "," : "") + subString
                    + (currentPointer == 0 ? "," : ""), "");
        }
    

    【讨论】:

    【解决方案5】:

    像这样使用正则表达式:

    String contents = "Monday,Tuesday,Wednesday";
    contents = contents.replaceAll("[\\,]+Tuesday|^Tuesday[\\,]*", "");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多