【问题标题】:Getting the length of a String value in StringTemplate在 StringTemplate 中获取字符串值的长度
【发布时间】:2013-03-06 23:06:51
【问题描述】:

According to the documentation 可以引用<object.property> 格式的对象属性。我希望这能让我检查字符串的长度,但它似乎不起作用。我认为这是因为该方法是String.length(),根据文档,如果我执行<mystr.length> 之类的操作,它将寻找一个名为getLength() 的方法和一个名为length 的字段,但它从不寻找方法叫length()。我在 Scala REPL 中通过这个快速检查进行了验证:

scala> import org.stringtemplate.v4._; import scala.collection.JavaConverters._;
import org.stringtemplate.v4._
import scala.collection.JavaConverters._

scala> new ST("<xs:{ x | <x>:<x.length> }>").add("xs", List("hello", "goodbye").asJava).render
res0: String = "hello: goodbye: "

scala> case class S(val s:String) { def getLength = s.length }
defined class S

scala> new ST("<xs:{ x | <x>:<x.length> }>").add("xs", List("hello", "goodbye").map(S).asJava).render
res1: String = "S(hello):5 S(goodbye):7 "

因此,如果 Strings 具有 getLength() 方法或 length 字段,它将起作用...

有没有更简单的方法来获取字符串长度?可能是内置的 StringTemplate 函数,或者其他我不知道的方法?

【问题讨论】:

    标签: string stringtemplate stringtemplate-4


    【解决方案1】:

    我在Cheatsheet's list of Functions:strlen找到了答案

    scala> new ST("<xs:{ x | <x>:<strlen(x)> }>").add("xs", List("hello", "goodbye").asJava).render
    res6: String = "hello:5 goodbye:7 "
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      相关资源
      最近更新 更多