java 自写replace()方法的实现

发布时间:2024-05-02 08:47 发布:上海旅游网

问题描述:

public static string replace(string test,string rep,string with);
//将test中的rep替换为with(不要使用jdk自带的replace)。 怎么实现呀

问题解答:

public static String rep(String source, String rep, String w) throws Exception {

   //get the index of the word you are going to replace

   int index = source.indexOf(rep);

   if(source.indexOf(rep) == -1)

      throw new Exception("Invalid input.");

   //separate the source word into 2 parts:

   //front part: before the word you want to replace

   //back part: after the word you want to replace

   String frontPart = source.substring(0,index);

   String backPart = source.substring(index+rep.length(), 

                                     source.length());

   return frontPart+w+backPart;

}

你应该知道你不能改变任何String类的东西,String 类是唯一个不能改变的类!!!!你如果需要加功能,你可以做个别的类extends String这个类,然后再overwrite它的replace方法。这个方法用.subString().equals("")也可以

热点新闻