2015-04-27 175 views
1

我是Scala的新手!我想计算一个字符串中发生字符的次数。我该怎么做呢?我开始写这样的东西,但我觉得语法很难理解。任何帮助?如何计算字符串的字符?

var s = "hello" 
var list = s.toList.distinct 
list.foreach(println(s.count(_=='list'))) 
+0

您是否在寻找字符串中字符总数的计数或字符串中每个唯一字符的计数? – cmbaxter

回答

2

你接近:

val s = "hello" 
val list = s.toList.distinct 
list.foreach(c => println(s.count(_ == c))) 

我已经改变了你的var s到val S,因为没有理由对他们来说是var秒。

请注意,没有任何理由将String转换为List

val s = "hello" 
s.distinct.foreach(c => println(s.count(_ == c))) 
+0

P.S.我喜欢cmbaxter的建议重写/重新思考。 –

3

试试这个:

小费,不要使用瓦尔它,如果你不仍然有效。

val l = "hello" 

scala> l.distinct.toCharArray.map(x=>(x,l.count(_==x))) 

res1: Array[(Char, Int)] = Array((h,1), (e,1), (l,2), (o,1)) 

它返回包含字符及其相关计数的(Char, Int)地图数组。

+0

这不起作用。它产生'Array((h,1),(e,1),(l,2),(l,2),(o,1))'。它会工作,如果它是'l.distinct.toCharArray' –

+0

@paul我不好,我粘贴错误的代码。我在REPL中测试了它,它们都是独特的,没有区别。我编辑过。 – curious

+1

这仍然比需要做更多的工作。你称之为重复计算每个重复的字母,重复计算相同的值。如果你做的是独特的第一个(l.distinct),那么只会发生一次每个不同的字母 –

7

你可以尝试这样的东西,如果你想要的字符的地图计数:

val str = "hello" 
val countsMap:Map[Char,Int] = 
    str. 
    groupBy(identity). 
    mapValues(_.size) 

这将扩展到更多的普通形式:

str. 
    groupBy(c => c). 
    mapValues(str => str.size) 

因此,要打破这,在groupBy中,我们说我们要在字符串本身中由个人Char组合。这将产生一个Map[Char, String]像这样:

Map(e -> e, h -> h, l -> ll, o -> o) 

然后,你Map的价值部分与mapValues方法重新映射告诉它使用的String,而不是String本身的.size

1

您可以轻松地组使用groupBy,然后测量长度的字符:

scala> "hello".toList.groupBy(identity) 
res0: scala.collection.immutable.Map[Char,List[Char]] = Map(e -> List(e), h -> List(h), l -> List(l, l), o -> List(o)) 

scala> res0.map { case (char, list) => (char, list.length) } 
res1: scala.collection.immutable.Map[Char,Int] = Map(e -> 1, h -> 1, l -> 2, o -> 1) 
1

或者,作为“不止一种方法去做一件事”

var s = "hello" 
s.foldLeft(Map[Char, Int]() withDefaultValue 0) 
      {(acc, c) => acc updated (c, acc(c)+1)} 
//> res0: scala.collection.immutable.Map[Char,Int] = 
    Map(h -> 1, e -> 1, l -> 2, o -> 1) 

一个说明和使用还有更多的Scala功能。这与groupBy/mapValues的答案基本相同,除了一次完成。