gpt4 book ai didi

java - 替换字符串中的单个字符

转载 作者:行者123 更新时间:2023-11-30 02:38:06 26 4
gpt4 key购买 nike

问题是需要替换给定字符串中的单个字符,同时保留字符串中的其他字符。

代码是:

    if(command.equalsIgnoreCase("replace single"))
{
System.out.println("Enter the character to replace");
String char2replace = keyboard.nextLine();
System.out.println("Enter the new character");
String secondChar = keyboard.nextLine();
System.out.println("Which " + char2replace + " would you like to replace?");
int num2replace = keyboard.nextInt();

for(int i=0; i< bLength; i++)
{

if(baseString.charAt(i)== char2replace.charAt(0))
{
baseString = baseString.substring(0, i) +
secondChar + baseString.substring(i + 1);

}

最佳答案

你几乎做到了,只需在循环中添加一个计数器即可:

int num2replace = keyboard.nextInt();
int count = 0;
for (int i = 0; i < bLength; i++) {
if (baseString.charAt(i) == char2replace.charAt(0)) {
count++;
if (count == num2replace){
baseString = baseString.substring(0, i) +
secondChar + baseString.substring(i + 1);
break;
}
}
if (char2replace.length() > 1) {//you need move this out of loop
System.out.println("Error you can only enter one character");
}


}
System.out.println(baseString);

关于java - 替换字符串中的单个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42570264/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com