我试图比较字符串的第一个字符,以确保它不等于数组中的任何位置。这是代码:
if(string.charAt(0) != array[0] || string.charAt(0) != array[1])
{
//Code here
}
我检查了一个在实际代码中有10个位置的数组,但是输入太多了。有更简单的方法吗?如果是这样,怎么样?
答案 0 :(得分:2)
使用for loop
for(int i = 0; i < array.length; i++){
if(string.charAt(0) != array[i])
{
//Code here
break;
}
}
或者甚至是while loop
int i = 0;
while(i < array.length){
if(string.charAt(0) != array[i])
{
//Code here
break;
}
}
为什么不能让螺旋迭代并做一些递归。 (假设数组的类型是char)。其他方法更好我只是想表明你可以用递归来做。
boolean checkChar(String string Char[] array){
return checkCharHelper(string, array, 0);
}
boolean checkCharHelper(String string, Char[] array, int index){
if(index >= string.length){
return false;
}
if(string.charAt(0) != array[i])
{
//Code here
return true;
}
return checkCharHelper(string, array, index + 1);
}
答案 1 :(得分:1)
Java 8 powa
int[] array = {'a','b','c'};
String s1 = "cat";
String s2 = "dog";
boolean res1 = Arrays.stream(array).anyMatch(c -> c==s1.charAt(0));
boolean res2 = Arrays.stream(array).anyMatch(c -> c==s2.charAt(0));
System.out.println(res1); //true
System.out.println(res2); //false
答案 2 :(得分:0)
for (char c : array) {
if (string.charAt(0) != c) {
// Code here
break;
}
}
答案 3 :(得分:0)
循环遍历数组并检查每个位置。如果找到匹配的标记,请设置标记。
boolean flag = false;
for (int i = 0; i < array.length; i++) {
if (string.charAt(0) == array[i]) {
flag = true;
break;
}
}
if (flag) {
// Indicates that one of them was equal.
} else {
// None of them was equal.
}
答案 4 :(得分:0)
使用List
代替静态数组,然后使用List#contains()
方法。
示例代码:
List<Character> list = Arrays.asList('a', 'b', 'c');
if (!list.contains(string.charAt(0))) {
System.out.println("not found in array");
}
答案 5 :(得分:0)
为迭代数组创建一个单独的方法,并将数组中的每个char与给定的char进行比较,在本例中是字符串的第一个字符。
private boolean charInArray(char[] chars, char c){
for(char x: chars)
if(c == x) return true;
return false;
}
您可以这样称呼它:
if(!charInArray(array, string.charAt(0)){
//do something
}
答案 6 :(得分:0)
我认为for循环是最好的选择。循环遍历数组,检查字符串开头的字符的每个索引。
//Your string
String yourString = "some string";
boolean interrupt = false;
for (int i = 0; i < array.length; i++) {
if(yourString.charAt(0).equalsIgnoreCase(array[i])) {
interrupt = true;
break;
}
}
if(interrupt) {
System.out.println("Found in array");
}
else {
System.out.println("Not found in array");