gpt4 book ai didi

java - 如何将 "****"字符串中的某个字符替换为作为输入的字符? java

转载 作者:行者123 更新时间:2023-11-30 04:07:52 26 4
gpt4 key购买 nike

以下是该方法的说明:

// Given a character, a String containing a word, and a String containing a 'guess'
// for that word, return a new String that is a modified version of the 'guess'
// string where characters equal to the character inChar are uncovered.
// For example, given the following call:
// modfiyGuess('G',"GEOLOGY", "**O*O*Y")
// This functions should return the String "G*O*OGY".

这是我的代码:

private static String modifyGuess(char inChar, String word, String currentGuess) {
int count= 0;
int occur= 0;
while (count < word.length()-1)
{
if(!(word.charAt(count)== inChar)){

count++;
}
else if(word.charAt(count)==inChar)
{
currentGuess= currentGuess.replace(currentGuess.charAt(count), inChar);
occur++;
count++;
}
}
System.out.println("The character " +inChar +" occurs in " +occur +" positions");
System.out.println(" ");
return currentGuess;
}

由于某种原因,如果在字符串 word 中找到了字符 inChar,则 currentGuess 将作为类似“GGGGGG”的字符串返回,用 inChar 替换字符串中的所有字符,而不是返回类似“G*** G”感谢您提供的任何答案!

最佳答案

如果是我,我会选择使用 for 循环而不是 while,这确实是个人喜好,但因为您需要迭代整个字符串,所以对于使用 for 时的 reader。

似乎你的 if 条件是彼此相反的。您检查它是否等于该字符,然后检查它是否等于。为什么不直接检查一下是否是这样,然后您就知道它不是了。这里字符串生成器用于构建字符串。如果要替换,则替换,如果不替换,我们会附加结果(名称已调整,因此您必须执行一些操作才能使用它。)

public static String modifyGuess(char letter, String word, String result) {
int occurrences = 0;
StringBuilder builder = new StringBuilder();
for(int i = 0; i < word.length(); ++i) {
if(word.charAt(i) == letter) {
builder.append(letter);
occurrences++;
} else {
builder.append(result.charAt(i));
}
}
System.out.println("\nThe character " + letter +" occurs in " + occurrences +" positions\n");
return builder.toString();
}

public static void main(String[] args){
String word = "GEOLOGY";
String result = "**OLO**";

result = modifyGuess('G', word, result);
System.out.println(result);
result = modifyGuess('E', word, result);
System.out.println(result);
result = modifyGuess('Y', word, result);
System.out.println(result);
}//SSCCE1

输出:

The character G occurs in 2 positions

G*OLOG*

The character E occurs in 1 positions

GEOLOG*

The character Y occurs in 1 positions

GEOLOGY

关于java - 如何将 "****"字符串中的某个字符替换为作为输入的字符? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20318887/

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