如何检查字符串中是否包含一个字符? [英] How to check if a character is contained in string?

查看:46
本文介绍了如何检查字符串中是否包含一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to check if the string contains the character. I am writing a hangman code. For example, here is the word to guess: "scala", but it looks like "_ _ _ _ _" tho the user. Let's assume that user inputs letter 'a', then it must look like "_ _ 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
    }
}

这样对吗?

提前致谢.

推荐答案

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

I don't think this is homework, so I'll probably regret answering if it is...

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

更新

好的,所以它看起来像家庭作业.我想现在精灵已经用完了,但除非你很快掌握 Scala 的速度,否则你将很难解释它是如何工作的.

Okay, so it does look like homework. I guess the genie's out of the bottle now, but unless you get up to speed on Scala very quickly you're going to have a really hard time explaining how it works.

这篇关于如何检查字符串中是否包含一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆