在 ruby​​ 中,如何判断字符串输入是大写还是小写? [英] In ruby how do you tell if a string input is in uppercase or lowercase?

查看:62
本文介绍了在 ruby​​ 中,如何判断字符串输入是大写还是小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序,当输入单个字母时,如果它是大写的,则将其保留为大写并返回,如果是小写,则转换为大写.我该怎么写才能判断字符串最初是大写还是小写?

I am trying to write a program that when a single letter is inputted, if it's in uppercase, leave it in uppercase and return it, and if it's in lowercase, then convert to uppercase. How do I write this to be able to tell if the string is originally in uppercase or lowercase?

推荐答案

只需将字符串转换为大写并与原始字符串进行比较

Just convert the string to upper case and compare it with the original

string == string.upcase

或小写

string == string.downcase

 

如评论中所述,上述解决方案仅适用于英文字母.如果您需要国际解决方案,请使用

as mentioned in the comments the solution above works with English letters only. If you need an international solution instead use

def upcase?(string)
    !string[/[[:lower:]]/]
end

它使用正则表达式来扫描字符串中的小写字母,然后否定结果以判断字符串是否全部为大写.

which uses a regular expressions to scan the string for lowercase letters and the negates the finding to tell whether the string is all uppercase.

这篇关于在 ruby​​ 中,如何判断字符串输入是大写还是小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆