Find the first un-repeated character in a string

后端 未结 30 1284
猫巷女王i
猫巷女王i 2020-11-27 18:29

What is the quickest way to find the first character which only appears once in a string?

30条回答
  •  时光取名叫无心
    2020-11-27 19:20

    In Ruby:

    (Original Credit: Andrew A. Smith)

    x = "a huge string in which some characters repeat"
    
    def first_unique_character(s)
     s.each_char.detect { |c| s.count(c) == 1 }
    end
    
    first_unique_character(x)
    => "u"
    

提交回复
热议问题