【问题标题】:fastest way for replacing i-th occurance in a string替换字符串中第 i 次出现的最快方法
【发布时间】:2016-08-07 17:24:03
【问题描述】:

我有一个字符串,它由总共 n 个相等的子字符串组成。例如,字符串"hellooo dddd" 有3 个"dd" 子字符串(我说它已经出现了3 次)。在更一般的情况下,我们在字符串中有 n 个相等的子字符串,我如何替换字符串中的第 i 个出现。一个类似replace() 的方法,用于第 i 个子字符串。我想在我的android代码中实现它。 (英语不是我的母语,如有错误请见谅。)。

【问题讨论】:

  • 迭代使用 String.indexOf(value,fromIndex)

标签: java android arrays string replace


【解决方案1】:
public static String replace(String input, String pattern, int occurence, String replacement){
    String result = input; 
    Pattern p = Pattern.compile(pattern); 
    Matcher m = p.matcher(result); 
    if(occurence == 0){ 
        return result; 
    } else if(occurence == 1){
        m.find();
        result = result.substring(0,m.start()) + replacement + result.substring(m.end());
    } else { 
        m.find();
        int counter = 1; 
        try { 
            while((counter<occurence)&&m.find(m.start()+1)){
                counter++; 
            }
            result = result.substring(0,m.start()) + replacement + result.substring(m.end());
        } catch(IllegalStateException ise){
            throw new IllegalArgumentException("There are not this many occurences of the pattern in the String."); 
        }
    }
    return result; 
}

如果我理解正确,似乎做的事情类似于你想要的。

使用匹配器/模式系统,它对更复杂的正则表达式开放。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 2018-09-17
    • 2016-05-07
    • 2011-06-05
    • 2011-08-25
    • 2018-08-11
    • 2016-11-02
    相关资源
    最近更新 更多