繁体   English   中英

在 Java 中不使用替换替换字符串中的单词

[英]Replace words in a string without using replace in Java

我正在尝试替换字符串中所有出现的单词。 但是,使用此代码,我只能找到它的第一次出现并替换它。 有没有办法扩展这段代码来替换整个字符串中的单词? 我试图在不使用 Java 中的替换内置方法的情况下执行此操作,因为我已经知道如何使用这些函数,我想知道是否还有其他方法可以解决此问题。

public static String replace(String old, String newWord, String input) {    

int i = input.indexOf(old);

if (i < 0) {
    return input;
}

    String partBefore = input.substring(0, i);
    String partAfter  = input.substring(i + old.length());

    return partBefore + newWord + partAfter;
}

首先,您需要某种循环。 大概有一段while

在循环中,由于您要替换“旧”字符串,因此您可以继续循环直到找不到它为止。 但是如果你想避免重新搜索字符串的第一部分,或者如果你想让替换包含它正在替换的字符串(而不是无限循环),那么一旦你完成了每个替换,使用String#indexOf(String str, int fromIndex) ,它允许您从字符串的中间继续。

public static String replace(String old, String newWord, String input) {    
    int i = input.indexOf(old);
    if (i < 0) {
        return input;
    }
    String partBefore = input.substring(0, i);
    String partAfter  = input.substring(i + old.length());
    return partBefore + newWord + replace(old, newWord, partAfter );
}

但是,在 StringBuilder 中收集点点滴滴更有效。

public static String replace(String oldStr, String newStr, String input) {    
    StringBuilder sb = new StringBuilder();
    int i;
    int prev = 0;
    while( (i = input.indexOf(oldStr, prev)) >= 0 ){
        sb.append( input.substring(prev, i) ).append( newStr );
        prev = i + oldStr.length();
    }
    sb.append(input.substring(prev));
    return sb.toString();
}

有一个使用递归的简单解决方案。 第一次替换字符串中的单词后,您可以通过再次调用 replace 方法替换字符串的partAfter部分中的单词:

public static String replace(String old, String newWord, String input) {    

    int i = input.indexOf(old);

    if (i < 0) {
        return input;
    }

    String partBefore = input.substring(0, i);
    String partAfter  = input.substring(i + old.length());

    return partBefore + newWord + 
           replace(old, newWord, partAfter); // <<-- Note recursion here 
}

这只会更改原始来源的一行。

首先,不要使用new作为变量名。 这是一个保留字。

其次,为了替换多次出现,你应该有一个循环。

最后,最好使用 StringBuilder 创建新的 String,而不是 String 连接。

这是未经测试的,但这样的事情应该可以工作:

public static String replace(String oldStr, String newStr, String input) {    

    int i = input.indexOf(oldStr);
    if (i < 0) {
        return input;
    }
    StringBuilder buffer = new StringBuilder();
    int prev = 0;
    while (i >= 0) {   
        String partBefore = input.substring(prev, i);
        prev = i + oldStr.length();
        buffer.append(partBefore);
        buffer.append(newStr);    
        i = input.indexOf(oldStr, i + oldStr.length());
    }
    buffer.append(input.substring(i+oldStr.length()));

    return buffer.toString();
}

使用递归:

public static String replaceAll(String old, String newWord, String input) {

    int i = input.indexOf(old);

    if (i < 0)
        return input;

    String partBefore = input.substring(0, i);
    String partAfter = input.substring(i + old.length());

    return replaceAll(old, newWord, partBefore + newWord + partAfter);
}

使用 do-While 并继续替换单词:

public static String replaceAll(String old, String newWord, String input) {

    boolean loop = true;

    do {
        int i = input.indexOf(old);

        if (i > 0) {

            String partBefore = input.substring(0, i);
            String partAfter = input.substring(i + old.length());
            input = partBefore + newWord + partAfter;

        } else
            loop = false;

    } while (loop);

    return input;
}

这是代码

import java.util.Scanner;
public class replacechar {
       String line;
       String s = "";
       char from ;
       char to ;
       public replacechar()
       {
           Scanner scan = new Scanner(System.in);
           System.out.println("Enter The String");
           line = scan.nextLine();
           System.out.println("Enter The Character you want to changer");
           from = scan.nextLine().charAt(0);
           System.out.println("Enter the Character you want to replace with");
           to = scan.nextLine().charAt(0);
           replacecharacter(from,to);
       }
       public void replacecharacter(char f,char t)
       {
           for(int i =0;i< line.length();i++)
           {

               if(line.charAt(i) == f)
               {
                  s += t;
               }
               else
               {
                   s += line.charAt(i);
               }

           }
           System.out.println(s);
       }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        replacechar  obj = new replacechar();
    }

}

不太确定 OP 是否仍在寻找答案,但它可能会帮助其他人。 这是我的代码,只有 for 循环和 java 的 substring 方法......

public static void main(String ar[])
{

 String str = "This is some string. replace lower case is with IS";
        String pattern = "is";
        String replaceWith = "IS"; // word to replace with
        System.out.println(replaceString(str, pattern, replaceWith));

    }

    static String replaceString(String str, String pattern, String replaceWith) {
        String temp = "";
        String replacedString = ""; // Replaced String
        int remainingString = 0; // append the rest of the string after last
                                    // occurance of pattern.
        for (int i = 0; i <= str.length() - pattern.length(); i++) {
            temp = str.substring(i, i + 1);

            if (str.substring(i, i + pattern.length()).equals(pattern)) {
                temp = replaceWith + " ";
                i += pattern.length();

            }
            remainingString = i;
            replacedString += temp;

        }
        replacedString += str.substring(remainingString + 1, str.length());

        return replacedString;
    }
}

在这里发布这个以防有人需要一个不使用 StringUtils 辅助方法的实现。


     static String replaceAll(String str, String oldW, String newW) {
            // code here
            char[] ch = str.toCharArray();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < ch.length;i++) {
                if (ch[i] == oldW.charAt(0) && checkForString(i+1,oldW,str)) {
                 sb.append(newW);
                 i += oldW.length() -1;
                }
                else
                    sb.append(ch[i]);
            }
            
            return sb.toString();
        }
        
        static boolean checkForString(int i, String str,String ogStr) {
            int start = i;
            for (int j = 1; j < str.length() && i < ogStr.length(); j++, i++) {
                if (ogStr.charAt(i) != str.charAt(j))
                    return false;
            }
            return (i-start+1) == str.length()?true:false;
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM