gpt4 book ai didi

scala - 如何检查字符串中是否包含字符?

转载 作者:行者123 更新时间:2023-12-05 09:25:16 24 4
gpt4 key购买 nike

我想检查字符串是否包含字符。我正在写一个刽子手代码。例如,这里是要猜测的词:“scala”,但它看起来像 “_ _ _ _ _” 用户。假设用户输入字母 'a',那么它必须看起来像 "_ _ a _ a"

def checkGuess(){
if (result.contains(user_input)) {
val comp = result.toCharArray
for (i <- comp){
if (user_input != comp(i))
comp(i) = '_'
comp(i)
}
val str = comp.toString
}
}

这样对吗?

提前谢谢你。

最佳答案

我不认为这是家庭作业,所以如果是...我可能会后悔回答

case class HangmanGame(goal: String, guesses: Set[Char] = Set.empty[Char]) {
override def toString = goal map {c => if (guesses contains c) c else '_'} mkString " "
val isComplete = goal forall { guesses.contains }
def withGuess(c: Char) = copy(guesses = guesses + c)
}

然后

val h = HangmanGame("scala")
h: HangmanGame = _ _ _ _ _

scala> val h1 = h.withGuess('a')
h1: HangmanGame = _ _ a _ a

scala> val h2 = h1.withGuess('l')
h2: HangmanGame = _ _ a l a

scala> val h3 = h2.withGuess('s')
h3: HangmanGame = s _ a l a

scala> val h4 = h3.withGuess('c')
h4: HangmanGame = s c a l a

scala> h4.isComplete
res5: Boolean = true

更新

好的,看起来确实像家庭作业。我猜 Sprite 现在已经从瓶子里出来了,但除非你很快掌握 Scala 的速度,否则你将很难解释它是如何工作的。

关于scala - 如何检查字符串中是否包含字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5055419/

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