编写一个方法,该方法返回字符串中使用的各种小写字母,大写字母,数字和特殊字符的No。利用范围。
输入=“ heLLo Every1”
我在提供的解决方案中使用范围和大小写方法。
解决方案:
bottomLeftView: {
flex: 1,
color: "black",
marginVertical: 5,
marginHorizontal: 5,
backgroundColor: "yellow",
height: 50,
alignSelf: "stretch",
textAlign: "center",
paddingLeft: 5,
textAlignVertical: "center"
}
代码有效。
答案 0 :(得分:2)
是
class String
def character_count
counters = Hash.new(0)
each_char do |item|
case item
when 'A'..'Z'
counters[:uppercase] += 1
when 'a'..'z'
counters[:lowercase] += 1
when '0'..'9'
counters[:digit] += 1
else
counters[:special] += 1
end
end
counters.values_at(:uppercase, :lowercase, :digit, :special)
end
end
if ARGV.empty?
puts 'Please provide an input'
else
string = ARGV[0]
uppercase, lowercase, digit, special = string.character_count
puts "Lowercase characters = #{lowercase}"
puts "Uppercase characters = #{uppercase}"
puts "Numeric characters = #{digit}"
puts "Special characters = #{special}"
end
答案 1 :(得分:1)
您可以按照以下更好的方式使用regex
,
type = { special: /[^0-9A-Za-z]/, numeric: /[0-9]/, uppercase: /[A-Z]/, lowercase: /[a-z]/ }
'Hello World'.scan(type[:special]).count
# => 1
'Hello World'.scan(type[:numeric]).count
# => 0
'Hello World'.scan(type[:uppercase]).count
# => 2
'Hello World'.scan(type[:lowercase]).count
# => 8
答案 2 :(得分:0)
其他选项。
首先,将您的范围映射到哈希中:
mapping = { upper: ('A'..'Z'), lower: ('a'..'z'), digits: ('0'..'9'), specials: nil }
然后将收件人哈希初始化为默认的0
:
res = Hash.new(0)
最后,映射输入的字符:
input = "heLLo Every1"
input.chars.each { |e| res[(mapping.find { |k, v| v.to_a.include? e } || [:specials]).first ] += 1 }
res
#=> {:upper=>3, :lower=>7, :digits=>1, :specials=>1}
答案 3 :(得分:0)
str = "Agent 007 was on the trail of a member of SPECTRE"
str.each_char.with_object(Hash.new(0)) do |c,h|
h[ case c
when /\d/ then :digit
when /\p{Lu}/ then :uppercase
when /\p{Ll}/ then :downcase
else :special
end
] += 1
end
end
#=> {:uppercase=>8, :downcase=>28, :special=>10, :digit=>3}