替换字符串中的字符,而不使用字符串replace()方法

时间:2013-12-18 11:11:03

标签: java swing

我有一个字符串,String originalString= "This car is my car";
我想用“自行车”代替“car”,而不使用字符串replace()方法。

class StringTest{
   public static void main(String[] args){
      String originalString = "This car is my car";
      String replacedString = replaceMethod(original, "car", "bike");
      System.out.println(replacedString);
   }  
}
static String replaceMethod( String original, String toReplace, String replacedWith){
    // enter code here
    return "";
}

5 个答案:

答案 0 :(得分:4)

您可以拆分“car”,然后连接“bike”

连接
import java.util.*;

class StringTest 
{
    public static void main(String[] args)
    {
        String originalString = "This car is my car";
        String replacedString = replaceMethod(originalString, "car", "bike");
        System.out.println(replacedString);
    }

    static String replaceMethod(String str, String from, String to) 
    {
        String[] arr = str.split(from);
        StringBuilder output = new StringBuilder();

        int i = 0;
        for (; i < arr.length - 1; i++)
        output.append(arr[i]).append(to);

        output.append(arr[i]);
        if (str.substring(str.lastIndexOf(" ")).equalsIgnoreCase(" " + from))
            output.append(to);

        return output.toString();
    }
}

originalString

This car is my car

输出

This bike is my bike

感谢Polywhirl先生的帮助。

答案 1 :(得分:2)

试试这个

static String replaceMethod(String original, String toReplace,
        String replacedWith) {
    for(;;) {
        int i = original.indexOf(toReplace);
        if (i == -1) {
            break;
        }
        original = original.substring(0, i) + replacedWith + original.substring(i + toReplace.length());
    }
    return original;
}

或者更好的是简单地复制Apache的StringUtils方法

public static String replace(String text, String searchString, String replacement, int max) {
    if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) {
        return text;
    }
    int start = 0;
    int end = text.indexOf(searchString, start);
    if (end == INDEX_NOT_FOUND) {
        return text;
    }
    int replLength = searchString.length();
    int increase = replacement.length() - replLength;
    increase = increase < 0 ? 0 : increase;
    increase *= max < 0 ? 16 : max > 64 ? 64 : max;
    StringBuilder buf = new StringBuilder(text.length() + increase);
    while (end != INDEX_NOT_FOUND) {
        buf.append(text.substring(start, end)).append(replacement);
        start = end + replLength;
        if (--max == 0) {
            break;
        }
        end = text.indexOf(searchString, start);
    }
    buf.append(text.substring(start));
    return buf.toString();
}

答案 2 :(得分:1)

假设这是家庭作业并且您正在寻找算法(这就是您不使用String.replace的原因),请记住字符串和数组基本相同,并且都可以迭代。

一种简单(低效)的算法:

1.创建一个子方法,以匹配主字符串中当前索引的子字符串。即。

private boolean matchAt(String inputString, String target, int index){
    // YOUR CODE HERE - returns 'true' if the target string occurs in the 
    // inputString at the specified index.
}

2.对输入字符串进行迭代,如果找到了目标字,则在每个字母处进行测试。

3.根据是否找到目标词,一次输出一个字符到StringBuilder。

要获得更有效的算法,请查看以下链接,了解如何使用后缀匹配实现字符串搜索:http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm

答案 3 :(得分:0)

这不是一个好方法,但我们也可以这样做

 public static void main(String[] args) {
      String org= "This car is my car";
      String [] temp=org.split(" ");
      int len=temp.length;
      String ne = "";
      for(int i=0;i<len;i++)
      {
          if(temp[i].matches("car"))
              temp[i]="bike";
          ne=ne+temp[i]+" ";

      }
        System.out.println(ne);
    }

答案 4 :(得分:0)

另一种选择......

import java.util.*;

class Replace {
    public static void main (String[] args) {
        String originalString = "This car is my car";
        String replacedString = replaceMe(originalString, "car", "bike");
        System.out.println(replacedString);
    }

    public static String replaceMe(String str, String from, String to) {
        String[] arr = str.split(" ");
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].equals(from)) {
                arr[i] = to;
            }
        }
        return join(arr, " ");
    }

    public static String join(String[] arr, String delim) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            sb.append(arr[i]);

            if (i < arr.length - 1)
                sb.append(delim);
        }
        return sb.toString();
    }
}