简体   繁体   English

如何在字符串数组中找到给定String的索引?

[英]How to find an index of given String in array of strings?

Surely the solution to this is the following: 当然,解决方案如下:

public long myFunc(String name) throws Exception {
    for(int i=0;i<amount;i++){ 
       if(this.otherString[i].equals(name)) 
           return longArray[i]; 
    } 
    throw new Exception("Not found"); 
} 

However, this does not seem to be the case. 但是,似乎并非如此。

You can use Guava, then your code can looks like this 您可以使用番石榴,然后您的代码可以如下所示

String[] stringArray = {"s1", "s2", "s3"};

int index = Iterators.indexOf(Iterators.forArray(stringArray), new Predicate<String>() {
    @Override
    public boolean apply(String input) {
        return input.equals("s2");
    }
});

or simpler 或更简单

int index = Arrays.asList(stringArray).indexOf("s2");

Your code can also look like this 您的代码也可以像这样

public class Finder {

    private String[] stringArray = {"s1", "s2", "s3"};

    public int findIndex(String name) {
        for (int i = 0; i < stringArray.length; i++) {
            if (stringArray[i].equals(name))
                return i;
        }

        throw new RuntimeException("Not found");
    }

    public static void main(String... s) {
        int index = new Finder().findIndex("s1");

        System.out.println(index);
    }
}

You can either run your code through a debugger and find out why it doesn't work, or add some println traces to your original code and you'll see what the problem is: 您可以通过调试器运行代码,找出为什么它不起作用,或者在原始代码中添加一些println跟踪,然后您将看到问题所在:

public long myFunc(String name) throws Exception {
    System.out.println("Looking for: " + name);
    for (int i = 0; i < amount; i++){
        if(this.otherString[i].equals(name))
            return longArray[i];
        System.out.printf("%4d: \"%s\": No match.%n", i, this.otherString[i]);
    }
    for (int i = amount; i < this.otherString.length; i++)
        System.out.printf("%4d: \"%s\": Not checked.%n", i, this.otherString[i]);
    throw new Exception("Not found");
}

By the way, make sure you are correctly interpreting the method's behaviour. 顺便说一句,请确保您正确解释了该方法的行为。 Could it be that it's finding it but throwing an ArrayIndexOutOfBoundsException because i is greater than longArray.length, and you misinterpret that as the exception you are explicitly throwing? 可能是因为找到了它却抛出了ArrayIndexOutOfBoundsException,因为i大于longArray.length,并且您误认为这是您明确抛出的异常?

Turns out '\' was at the end of the string that was meant to be equal. 原来,'\\ u0000'位于要等于的字符串的末尾。 This does not show in printing. 在打印中不显示。 Next time I will be more ruthless in the inspection of the debugging. 下次我将更加无情地检查调试。 Thank you for all the suggestions though, and sorry for wasting your time. 谢谢您的所有建议,也很抱歉浪费您的时间。

This might be completely wrong, but isn't the problem just missing curly brackets in the if statement? 这可能是完全错误的,但是问题不仅仅在于if语句中缺少大括号吗? I am new to the java language and the example is probably messy, but it uses the same structure from your question and works just fine: 我是Java语言的新手,该示例可能很凌乱,但是它使用了与您的问题相同的结构,效果很好:

public class random_class {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String[] a = new String[] {"hi!", "hello world!", "ho ho ho world!"};       
    int b = getHWIndex(a);
    System.out.println(b);
}

public static int getHWIndex(String[] stringArray){
    int i;
    Boolean test = false;
    for(i=0;i<stringArray.length;i++){
        if(stringArray[i].equals("hello world!")){
            test = true;  
            break;
        }
    }
    if(test == true){
    return i;}else{
        return i = 0; // this is not a good answer... 
//but as you return an int I could not think on a quick way to fix   the return when there is no match.
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 给定一个字符串数组,如何找出特定字符串的索引? - Given an array of Strings, how to find out the index of a particular String? 如何从给定的值中找到 Java 中 STRING 数组的索引? - How to find index of STRING array in Java from a given value? 对于给定的字符串数组,如何在字符串的索引处打印该字符串的字符 - How would you print out the character of that string at the index of the string for a given array of Strings 如何找到数组中给定int的每个索引? - How to find every index of a given int in an array? 给定一个字符串数组,编写一个递归方法,在 O(n) 中搜索给定字符串并返回索引。 LMK 如何修复错误 - Given an array of strings, write a recursive method that searches for a given string in O(n) and returns the index. LMK how to fix error 如何在字符串数组中的特定索引处追加String - How to append String at particular index in an array of Strings 在可能发生重叠的字符串数组中查找字符串的索引 - Find index of string in an array of strings where overlap could occur 删除给定字符串中的数组字符串? - remove the array strings in the given string? 如何将字符串插入字符串数组中的特定索引并在此之后移动字符串? - How to Insert string to a particular index in string array and shifting strings after that? 查找字符串数组的索引 - Find index of a string array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM