替换字符串中的字符,不使用字符串 replace() 方法 [英] Replace characters in a string, without using string replace() method
本文介绍了替换字符串中的字符,不使用字符串 replace() 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,String originalString="This car is my car";
我想用自行车"替换汽车",而不使用字符串 replace()
方法.
I have a String , String originalString= "This car is my car";
I want to replace "car" with "bike", without using string replace()
method.
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 "";
}
推荐答案
可以拆分car",然后添加bike"连接
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();
}
}
原始字符串
This car is my car
输出
This bike is my bike
感谢 Polywhirl 先生的帮助.
Thanks for Mr. Polywhirl for his help.
这篇关于替换字符串中的字符,不使用字符串 replace() 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文