如何从字符串行获取小写字符串和数字字符串然后将它们放入List?

时间:2017-06-30 08:42:46

标签: scala

如何从字符串行获取小写字符串和数字字符串,然后将它们放入List

val s: String = "ab12%3kk45@"

期望:

val result: List[String] = List("ab","12","3","kk","45")

2 个答案:

答案 0 :(得分:5)

您可以使用正则表达式:

scala> val result = """[0-9]+|[a-z]+""".r.findAllIn(s).toList
result: List[String] = List(ab, 12, 3, kk, 45)

此表达式匹配带[0-9]+的数字的连续子字符串,或带[a-z]+的小写字母的连续子字符串,findAllIn方法查找所有此类子字符串。

答案 1 :(得分:0)

这是有趣的答案(因为我正在为CS采访做准备:)没有实用方法)。这个想法只是创建保持缓冲属于相同ascii范围的字符。

只要看到不属于ascii范围的内容,请将当前缓冲区添加到列表

def extractIsomorphicChars(input: String): ListBuffer[String] = {

  var previousChar = ' '

  var ismorphicList = new scala.collection.mutable.ListBuffer[String]

  var isomorphicChars = ""

  input.zipWithIndex.foreach { case (currentChar, index) =>

    if ((48 to 57 contains currentChar.toInt) ||
      (65 to 90 contains currentChar.toInt) ||
      (97 to 122 contains currentChar.toInt)) {

      if (index == 0) {
        isomorphicChars = isomorphicChars + currentChar
      } else if (
        (List(currentChar.toInt, previousChar.toInt) forall (48 to 57).contains) ||
          (List(currentChar.toInt, previousChar.toInt) forall (65 to 90).contains) ||
          (List(currentChar.toInt, previousChar.toInt) forall (97 to 122).contains)) {
        isomorphicChars = isomorphicChars + currentChar
        if (index == input.length - 1) {
          ismorphicList += isomorphicChars
        }
      } else {
        if (isomorphicChars.nonEmpty) {
          ismorphicList += isomorphicChars
          isomorphicChars = ""
        }
        isomorphicChars = isomorphicChars + currentChar
      }

    } else if (isomorphicChars.nonEmpty) {
      ismorphicList += isomorphicChars
      isomorphicChars = ""
    }

    previousChar = currentChar
  }
  ismorphicList
}

测试

extractIsomorphicChars("ab12%3kk45@") shouldBe ListBuffer("ab", "12", "3", "kk", "45")
extractIsomorphicChars("aaaaaa") shouldBe ListBuffer("aaaaaa")
extractIsomorphicChars("123456") shouldBe ListBuffer("123456")
extractIsomorphicChars("") shouldBe ListBuffer()
extractIsomorphicChars("abc ") shouldBe ListBuffer("abc")
extractIsomorphicChars("%%     ") shouldBe ListBuffer()
extractIsomorphicChars(">%%%<") shouldBe ListBuffer()