繁体   English   中英

如何在不使用Java中的替换功能的情况下替换字符串中的字符?

[英]How to replace character in string without using the replace function in Java?

所以我要求输入一个字符串,然后我问用户想要对字符串做什么,在这种情况下,我试图替换第一次出现的字符。 我可以询问要替换的内容以及替换的内容。 我也知道如何进行一些替换,但是如果字符串有 2 个相同的字符,我会得到一个新的字符串

(将 i 更改为 o:(输入)“Find Dime” --->(输出)“Fond Dime”和“Find Dome”)

我只需要第一个。

else if (UserCommand.equalsIgnoreCase("replace first"))
    {
        System.out.println("Enter the character to replace");
        String Replace = input.next();
        System.out.println("Enter the new character");
        String Replacement = input.next();
        for (int i = 0; i<String.length();i++)
        {
            if (String.charAt(i)==Replace.charAt(0)) 
            {
                StringEdit = String.substring(0,i) + Replacement + String.substring(i + Replace.length());
            }
        }

输出:

Enter the string lump sum Enter the character to replace u Enter the new character o lomp sumlump som

如果您只需要第一个 String 使用

break;

在 if 语句中

暂无
暂无

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

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