代码之家  ›  专栏  ›  技术社区  ›  Mantas Vidutis

字符串第一个字符的大小写

  •  3
  • Mantas Vidutis  · 技术社区  · 15 年前

    我需要根据第一个字符决定一个字符串,并且我有一个这样定义的方法:

    (defn check-first [string]
      (case (get string 0)
        "+" 1
        "-" 2
        3
        ))
    

    当前,即使字符串以这些字符开头,它也始终返回3。我做错什么了?另外,有没有一种更优雅的方法来实现这一点?

    3 回复  |  直到 15 年前
        1
  •  10
  •   MayDaniel    15 年前
    (get "foo" 0)
    ;; => \f
    

    (get "foo" 0) 返回 char ,不是 string ,因此,如果您想使用 check-first ,您需要用字符替换字符串。

    (defn check-first [s]
      (case (first s) \+ 1, \- 2, 3))
    

    顺便说一句, Clojure Library Coding Standards 建议使用 s 作为需要字符串输入的函数的参数名。

    如果您希望使用字符串代替字符: (str (first "foo")) (subs "foo" 0 1) => "f"

    或者,可以写一个 case-indexed 宏。

    下面是一个快速的黑客程序,没有为默认表达式提供任何选项:

    (defmacro case-indexed [expr & clauses]
      (list* 'case expr (interleave clauses (iterate inc 1))))
    
    ;; (case-indexed "foo" "bar" "baz" "foo") => 3
    ;; (case-indexed (+ 5 1) 3 4 5 6 7) => 4
    
    (defn check-first [s]
      (case-indexed (first s)
        \+, \-, \*, \/))
    

    我不认为我会把这些条款分开——只是为了让答案更简洁。

    我建议延长 病例索引 但是,对于默认表达式,如果要使用它的话。也, 先检查一下 这个函数的名称似乎太笼统了;我没有更好的建议,但我会考虑更改它。(假设这不是为了这个问题而编造的。)

        2
  •  3
  •   Michael Kohl    15 年前

    您可以保留您所拥有的,并在您的情况下使用Java的子字符串方法:

    (defn check-first [s]
      (case (.substring s 0 1)
        "+" 1
        "-" 2
        3))
    

    编辑:刚刚注意到梅丹尼尔已经提到 subs ,其工作方式与 .substring . 对不起,这里太早了…

        3
  •  -3
  •   Nikki9696    15 年前

    你想用康德吗?

    http://clojure-notes.rubylearning.org/

    (def x 10)
    (cond
    (< x 0) (println "Negative!")
    (= x 0) (println "Zero!"))
    ; => nil
    
    (cond
    (< x 0) (println "Negative!")
    (= x 0) (println "Zero!")
    :default (println "Positive!"))
    ; => Positive!