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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20656523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:22:05  来源:igfitidea点击:

Replace characters in a string, without using string replace() method

javaswing

提问by user3114910

I have a String , String originalString= "This car is my car";
I want to replace "car" with "bike", without using string replace()method.

我有一个 String ,String originalString= "This car is my car";
我想用“bike”替换“car”,而不使用 stringreplace()方法。

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 "";
}

回答by Ahmed Hamdy

You can split on "car" and then concatenate with adding "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

output

输出

This bike is my bike

Thanks for Mr. Polywhirl for his help.

感谢 Polywhirl 先生的帮助。

回答by Lijo

this is not a good method but we can also do like this

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

 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);
    }

回答by Evgeniy Dorofeev

try this

尝试这个

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;
}

or better yet simply copypaste Apache's StringUtils method

或者更好的是简单地复制粘贴 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();
}

回答by Mr. Polywhirl

Another alternative...

另一种选择...

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();
    }
}

回答by Alex

Assuming that this is homework and you are looking for an algorithm (which is why you aren't using String.replace), just remember that strings and arrays are basically identical and can both be iterated.

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

A simple (inefficient) algorithm:

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

1.Create a submethod to match a substring against the current index in the main string. i.e.

1.创建一个子方法来将子字符串与主字符串中的当前索引进行匹配。IE

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.Iterate over the input string, testing at each letter if the target word has been found.

2.迭代输入字符串,测试每个字母是否找到目标词。

3.Append output one character at a time to a StringBuilder, based on whether or not the target word has been found.

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

For a more efficient algorithm, check out the following link on how string search can be implemented using suffix matching: http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm

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