2011-09-03 13 views
13

मैं स्ट्रिंग को वैकल्पिक शब्दों में विभाजित करना चाहता हूं। हमेशा एक संख्या भी होगी।वैकल्पिक शब्दों में स्प्लिट स्ट्रिंग (स्कैला)

उदा।

val text = "this here is a test sentence" 

कुछ आदेश दिया संग्रह जो मुझे के रूप में सही परिणाम देता है मैं

val (l1, l2) = text.split(" ").zipWithIndex.partition(_._2 % 2 == 0) match { 
    case (a,b) => (a.map(_._1), b.map(_._1))} 

ले कर आए हैं

"this", "is", "test" 

और

"here", "a", "sentence" 

युक्त प्रकार के बदलने चाहिए दो Arrays।

क्या यह और अधिक सुंदर ढंग से किया जा सकता है?

+0

@Paul:> वैल पाठ स्केला = पाठ "इस यहाँ एक परीक्षण वाक्य है" सहमत हैं, 'transpose' – elm

उत्तर

27
scala> val s = "this here is a test sentence" 
s: java.lang.String = this here is a test sentence 

scala> val List(l1, l2) = s.split(" ").grouped(2).toList.transpose 
l1: List[java.lang.String] = List(this, is, test) 
l2: List[java.lang.String] = List(here, a, sentence) 
+4

+1 मिटा दिया गया क्या एक शानदार समाधान है! :) – agilesteel

+1

के लिए टैग –

2

तो, कैसे इस बारे में: java.lang.String = इस यहाँ एक परीक्षण वाक्य

है
scala> val Reg = """\s*(\w+)\s*(\w+)""".r 
Reg: scala.util.matching.Regex = \s*(\w+)\s*(\w+) 


scala> (for(Reg(x,y) <- Reg.findAllIn(text)) yield(x,y)).toList.unzip 
res8: (List[String], List[String]) = (List(this, is, test),List(here, a, sentence)) 

scala> 
संबंधित मुद्दे