如何编写一个Loop来替换字符串中出现的字符?

时间:2016-02-20 20:46:44

标签: java regex string

这是我从早上开始尝试做的事情,但到目前为止还没有运气。

  

不使用String的“regex” replace(),但只使用循环,编写一个替换出现字符串的方法来自 parentString 与其他内容。

我能够实现一个版本,其中type char replaceWith将被替换,但如果要替换type String replaceWith,则没有运气,如下面的模板所示。

public String replaceWith(String parentString, String occurrence, String replaceWith){
      String newString; //Initialize

      //loop through "parentString", 
      //find and replace "occurence" with "replaceWith"

 return newString;
}

4 个答案:

答案 0 :(得分:1)

使用字符串搜索算法,该算法根据发生的长度检查所有字符的出现字符。像Rabin-Karp算法这样的东西

function NaiveSearch(string s[1..n], string pattern[1..m])
    for i from 1 to n-m+1
      for j from 1 to m
         if s[i+j-1] ≠ pattern[j]
            jump to next iteration of outer loop
       return i
    return not found

答案 1 :(得分:0)

类似的东西:

public String replace(String source, String target, String replacement) {
    int targetLength = target.length();

    int sourceLength = source.length();
    if (sourceLength < targetLength) {
        return source;
    }

    String result = source;

    for (int i = 0;  i< sourceLength - targetLength; i++) {
        String before = result.substring(0, i);
        String substring = result.substring(i, i+targetLength - 1);
        String after = result.substring(i + targetLength);
        if (substring.equals(target)) {
            result = before.concat(replacement).concat(after);
        } 
    }

    return  result;
}

答案 2 :(得分:0)

我的快速解决方案就是这样。不保证所有输出都是正确的。

public static String replaceWith(String s, String find, String replace) {
    StringBuilder sb = new StringBuilder();
    int findLength = find.length();
    int sourceLength = s.length();

    for (int i = 0; i < sourceLength; i++) {
        String nextSubstring;
        if (i + findLength >= sourceLength) {
            nextSubstring = s.substring(i);
        } else {
            nextSubstring = s.substring(i, i + findLength);
        }

        if (nextSubstring.equals(find)) {
            sb.append(replace);
            i += findLength - 1;
        } else {
            sb.append(s.charAt(i));
        }
    }

    return sb.toString();
}

样本测试

replaceWith("Hello World", "Hello", "World") => "World World"
replaceWith("HelloHelloWorld", "Hello", "World") => "WorldWorldWorld"
replaceWith("I replace banana, banana and some more banana", "banana", "apple") => I replace apple, apple and some more apple

答案 3 :(得分:-1)

我写了这个快速解决方案:

I replace apple, apple and some more apple

你可以在这里看到这个:enter image description here 它输出:

$top50raw1 = Invoke-WebRequest "http://www.ariacharts.com.au/chart/singles"