代码之家  ›  专栏  ›  技术社区  ›  stack0114106

scala-从上到下打印供应商细分

  •  2
  • stack0114106  · 技术社区  · 6 年前

    /Vendor/Platform/DataServices 
    

    /Vendor/
    /Vendor/Platform/
    /Vendor/Platform/DataServices
    

    现在,我使用下面的函数,

    scala> def hier_str(a:String,b:Int):String =
         | {
         |
         | for(i<- a.zipWithIndex.filter(_._1=='/').map(x => x._2 ).zipWithIndex )
         | if( i._2 == b )
         | return a.substring(0,i._1)
         |
         | return a
         |
         | }
    hier_str: (a: String, b: Int)String
    
    scala> for(i<- 1 to 3) yield hier_str("/Vendor/Platform/DataServices",i)
    res40: scala.collection.immutable.IndexedSeq[String] = Vector(/Vendor, /Vendor/Platform, /Vendor/Platform/DataServices)
    
    scala>
    

    3 回复  |  直到 6 年前
        1
  •  4
  •   BlueSheepToken    6 年前

    你要找的是 scanLeft 方法,该方法出现在scala 2.8中

    scan 就做一个 fold 并存储中间结果:

    string.split('/').drop(1).scanLeft(""){(acc, next) => acc + "/" + next}.drop(1)
    

    打印每个元素时的输出:

    /Vendor
    /Vendor/Platform
    /Vendor/Platform/DataServices
    

    查看官方文件 https://www.scala-lang.org/api/2.12.3/scala/collection/TraversableLike.html

    https://scalafiddle.io/sf/A7GEFaM/10

        2
  •  1
  •   Bruno Paulino    6 年前

    这个小功能可以做到:

    def split(path: String): String = {
      val filteredList = path.split("/").zipWithIndex.filter(_._1.nonEmpty)
      filteredList.map {
        case (text, index) =>
          (0 until index).map(i => filteredList(i)._1).mkString("/")
      }.mkString("\n")
    }
    
    split("/Vendor/Platform/DataServices")
    /* should output
    Vendor/
    Vendor/Platform/
    Vendor/Platform/DataServices
    */
    
        3
  •  1
  •   Tim    6 年前

    a
      .split("/")
      .filter(_.nonEmpty)
      .inits
      .map(_.mkString("/","/",""))
      .toList
      .reverse
    

    这包括根元素 / 所以加上 .drop(1) 如果你不想要这个。

    这可能比使用自定义函数的代码好,也可能不好。。。

        4
  •  0
  •   ishwar    5 年前

    我认为这将解决您的问题:

    val str1="/Vendor/Platform/DataServices"
    val p=str1.split('/').drop(1).scanLeft(""){case (x, y) => x + "/" + y}.drop(1).mkString("/"+"\n")
    println(p)