String[] directions = {"UP","DOWN","RIGHT","LEFT"};
String input = "DOWN 123 test";
有没有办法检查输入字符串 startwith 方向中的一个值而不使用拆分输入值?
答案 0 :(得分:7)
当然 - 只是遍历所有方向:
private static final String[] DIRECTIONS = {"UP","DOWN","RIGHT","LEFT"};
public static String getDirectionPrefix(String input) {
for (String direction : DIRECTIONS) {
if (input.startsWith(direction)) {
return direction;
}
}
return null;
}
或使用Java 8的流:
private static final List<String> DIRECTIONS = Arrays.asList("UP","DOWN","RIGHT","LEFT");
public static Optional<String> getDirectionPrefix(String input) {
return DIRECTIONS.stream().filter(d -> input.startsWith(d)).findFirst();
}
答案 1 :(得分:1)
遍历String数组并使用 <xsl:for-each select="//complextype[@name='submission']">
<td width="40%"><u>From date:</u><br/><xsl:value-of select="submission-period-from-date"/><br/></td>
<td width="40%"><u>To date:</u><br/><xsl:value-of select="submission-period-to-date"/><br/></td>
</xsl:for-each>
函数。
String startsWith
<强>输出强>
public static void main(String[] args) {
String[] directions = { "UP", "DOWN", "RIGHT", "LEFT" };
String input = "DOWN 123 test";
for (String s : directions) {
if (input.startsWith(s)) {
System.out.println("Yes - "+s);
break;
} else {
System.out.println("no - "+s);
}
}
}
答案 2 :(得分:1)
在您的情况下,您必须遍历数组并使用String.startsWith()
方法。
for(String direction : directions) {
if(input.startsWith(direction) {
// Do something
}
}
答案 3 :(得分:0)
请检查以下代码。
String[] directions = {"UP","DOWN","RIGHT","LEFT"};
String input = "DOWN 123 test";
for(String dir:directions){
if(input.startsWith(dir)){
System.out.println("input string starts with:"+dir);
}
}