Java 如何检查某个位置的字符串是否包含字符啊?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21587658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:31:25  来源:igfitidea点击:

How to check if a string at a certain position contains character a-h?

javaif-statementchar

提问by ToonLink

I know there must be a simpler way to check, but this is what I'm doing right now.

我知道必须有一种更简单的检查方法,但这就是我现在正在做的。

if (g.charAt(0) == 'a' || g.charAt(0) =='b' || g.charAt(0) =='c' ||
    g.charAt(0) == 'd' || g.charAt(0) =='e' || g.charAt(0) =='f' ||
    g.charAt(0) == 'g' || g.charAt(0) =='h')

采纳答案by user2864740

Relying on character ordering and that a..h is a consecutive range:

依靠字符排序并且a..h 是一个连续的范围

char firstChar = g.charAt(0);
if (firstChar >= 'a' && firstChar <= 'h') {
   // ..
}

回答by Makoto

Use a regular expression for this one. Cut the first character of your String as a substring, and match on it.

为此使用正则表达式。将 String 的第一个字符剪切为子字符串,并对其进行匹配。

if(g.substring(0, 1).matches("[a-h]") {
    // logic
}

回答by hemanth

Another way of doing it :

另一种方法:

if(Array.asList("abcdefgh".toCharArray()).contains(g.charAt(0)))
{
  //Logic
}

回答by Mario Carneiro

A variation on hemanth's answer:

hemanth 答案的变体:

if("abcdefgh".contains(g.substring(0,1))) do_something();

or

或者

if("abcdefgh".indexOf(g.charAt(0)) >= 0) do_something();