【问题标题】:Alternate for replace() or replaceAll() methodsreplace() 和 replaceAll() 方法的替代方法
【发布时间】:2014-03-08 17:29:49
【问题描述】:

我们有一个要求,我们必须替换一个字符串。但是我们不应该使用 replace() 或 replaceAll() 方法。我们如何在 Java 中实现这一点?

例如:

第一串:生活是实际的 (这里 Life 字符串必须替换为 'Everything in the world')

预期输出: 世间万物皆实用

【问题讨论】:

  • 为什么不能实现自己的替换方法?
  • 去String类..看看replace和replaceall方法的实现...然后你可以自己做
  • 没有。我们的要求是不要使用 replace() 方法
  • @VishalSantharam 我该怎么做??

标签: java string replace


【解决方案1】:

检查这个。

public class ReplaceTest {

public static void main(String[] args) {
    String str = "Life is practical";  //At first
    testReplace(str);

    str = "I have Life"; //At last
    testReplace(str);

    str = "I have Life, Life is beautiful"; //in the mid
    testReplace(str);


}

private static void testReplace(String str) {
    String[] strArr = str.split("Life");
    StringBuilder newStr = new StringBuilder(strArr[0]);
    for (int i = 1; i < strArr.length; i++) {
        newStr.append("Everything").append(strArr[i]);
    }

    if (str.endsWith("Life")) {
        newStr.append("Everything");
    }
    System.out.println(newStr.toString());

}

}

输出:
一切实用
我什么都有
我拥有一切,一切都很美好

【讨论】:

  • 如果您得到了答案,请将解决方案勾选为已接受。谢谢
【解决方案2】:

这样就可以了..

return firstString.substring(0,firstString.indexOf(strPrevString))+strNextString+firstString.substring(firstString.indexOf(strPrevString)+strPrevString.length(),firstString.length());

strPrevString=生活是实际的;

strNextString=世界上的一切

【讨论】:

    【解决方案3】:

    从Java源代码修改:

     public String customReplaceAll(String sourceString ,String regex, String replacement) 
         {      
           return Pattern.compile(regex).matcher(src).replaceAll(replacement);
         }
    

    用法:

    System.out.println(customReplaceAll("Hi da Hi","Hi","Bye")); 
    

    O/P:

    Bye da Bye
    

    【讨论】:

    • 感谢您的工作。但是在上面的代码中,你又在使用 replaceAll() 方法???我想要只有正则表达式的东西??
    • 替换模式的方法id不是字符串。
    猜你喜欢
    • 2021-11-16
    • 1970-01-01
    • 2016-06-08
    • 2012-10-08
    • 2011-05-05
    • 2019-01-13
    • 2016-06-20
    • 1970-01-01
    • 2012-09-25
    相关资源
    最近更新 更多