微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何递归地使用 replaceAll() 函数?

如何解决如何递归地使用 replaceAll() 函数?

该程序应该允许用户输入一个字符串,一个他们希望找到的子字符串和 他们希望替换找到的子字符串的另一个字符串。

你的程序的输出应该类似于下面给出的输出

请输入字符串:Hello world

请输入您要查找的子字符串:llo

请输入一个字符串来替换给定的子字符串:@@

你的新字符串是:he@@world

我是 Java 新手,找不到,到目前为止,这是我所拥有的:

import java.util.Scanner;

public class searchReplace 
{
    static String word,substring,newWord;
    static String output = "";
    

    public static void main(String[] args) 
    {
        Scanner input = new Scanner(system.in);
        
        System.out.println("Please enter a string: ");
        word = input.next();
        
        System.out.println("Please enter the substring you wish to find: ");
        substring = input.next();
        
        System.out.println("Please enter a string to replace the given substring: ");
        newWord = input.next();
        
        replace(substring,newWord);
        
        
        
        input.close();


    }


    private static void replace(String substring,String newWord) 
    {
        if(output.contains(newWord))
        {
            System.out.println(output);
        }
        
        else
        {
            output = word.replaceAll("substring","newWord");
            replace(substring,newWord);
        }
        
    }

}

我得到了错误

线程“main”中的异常java.lang.NullPointerException:无法调用“String.contains(java.lang.CharSequence)”,因为“searchReplace.output”为空 在 searchReplace.replace(searchReplace.java:33) 在 searchReplace.main(searchReplace.java:21)

解决方法

为了您的目标,您只需使用:

output = word.replace(substring,newWord);

代替:

word.replaceAll("substring","newWord");

您不需要进行任何递归。替换函数将在每次出现时用 newWord 替换 word 中的子字符串。

,

不需要递归:

public static void main(String [] args) {
    try (Scanner scanner = new Scanner(System.in)) {
        System.out.println("Enter String: ");
        String input = scanner.nextLine();
        System.out.println("String to replace: ");
        String toReplace = scanner.nextLine();
        System.out.println("Replace with: ");
        String replaceWith = scanner.nextLine();
        
        System.out.println(input.replaceAll(toReplace,replaceWith));
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。