确定字符串是否以字母 A 到 I 开头
我有一个简单的java作业。我需要确定一个字符串是否以字母 A 到 I 开头。我知道我必须使用 string.startsWith();但我不想一直写 if(string.startsWith("a"));
,这似乎效率不高。我应该使用某种循环吗?
I've got a simple java assignment. I need to determine if a string starts with the letter A through I. I know i have to use string.startsWith(); but I don't want to write, if(string.startsWith("a"));
all the way to I, it seems in efficient. Should I be using a loop of some sort?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
为此,您不需要正则表达式。
尝试一下,假设您只需要大写:
但是,如果您确实需要正则表达式解决方案,则可以使用此解决方案 (ideone) :
You don't need regular expressions for this.
Try this, assuming you want uppercase only:
If you do want a regex solution however, you can use this (ideone):
应该做
should do it
为了简洁起见,这个怎么样?
How about this for brevity?
尝试
Try
这使得将其作为一种方法提取变得很容易:
这比任何内联解决方案都更受欢迎。为了获胜,将其标记为 Final,以便 java 为您内联它,并为您提供比编码内联解决方案更好的性能。
This makes it easy to extract it as a method:
which is HIGHLY preferred to any inline solution. For the win, tag it as final so java inlines it for you and gives you better performance than a coded-inline solution as well.
if ( string.toUpperCase().charAt(0) >= 'A' && string.toUpperCase().charAt(0) <= 'I' )
应该是最简单的版本......
if ( string.toUpperCase().charAt(0) >= 'A' && string.toUpperCase().charAt(0) <= 'I' )
should be the easiest version...