[英]How to replace character in string without using the replace function in Java?
So I am asking for a string to be inputted, then I am asking what the user wants to do to the string, in this case, I am trying to replace the first occurrence of a character.所以我要求输入一个字符串,然后我问用户想要对字符串做什么,在这种情况下,我试图替换第一次出现的字符。 I can ask for what wants to be replaced and what to replace it with.
我可以询问要替换的内容以及替换的内容。 I also know how to do the replacement somewhat, but say if the string has 2 of the same characters, I get a new String for both
我也知道如何进行一些替换,但是如果字符串有 2 个相同的字符,我会得到一个新的字符串
(Change i to o: (input)"Find Dime" --->(output) "Fond Dime" & "Find Dome") (将 i 更改为 o:(输入)“Find Dime” --->(输出)“Fond Dime”和“Find Dome”)
I only need the first one.我只需要第一个。
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());
}
}
Output:输出:
Enter the string lump sum Enter the character to replace u Enter the new character o lomp sumlump som
if you only need the first String use如果您只需要第一个 String 使用
break;
in the if statement在 if 语句中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.