有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何解决java编程语言中的索引问题

public static int indexOf(String text , char index){

        char array [] = new char[text.length()];
        for(int i = 0 ; i < text.length(); i++){
            array[i] = text.charAt(i);
        }// end of first loop
        // the above loop converts the string obj to char array

        for(int i = 0 ; i < array.length; i++){
            if(array[i] == index){ // if a given letter is exist in string 
                System.out.println("The index of " + index + " is " + i);
                return i; // show or return the index of that given letter
            }
        }//end of second loop 
        System.out.println("The Letter you Entered does not Exist");
        return -1;
    }// end of method 

这段代码用于查找字符串的索引; 首先,它将一个字符串和一个字符作为输入,然后将其转换为字符数组,然后搜索给定的letter(如果找到)。 方法将返回其索引,但主要问题是字符串中有多个相同的字母,因此它将返回第一个字母。 我如何检测第二个字母,或者如何区分第二个相同的字母,并显示它是索引,例如:

indexOf(“国王小丑”,k')

在kingjoker字符串中,我们有两个k字母,方法无法找到第二个k索引,这就是问题所在


共 (1) 个答案

  1. # 1 楼答案

    • 将方法的返回类型更改为int[]
    • 沿着绳子走一圈,数一数火柴
    • 制作一个大小等于计数的数组
    • 再次遍历字符串,边走边填充返回索引

    以下是您修改后的实现:

    public static int[] indexesOf(String text , char ch) {
        int count = 0;
        for (int i = 0 ; i != text.length() ; i++) {
            if (text.charAt(i) == ch) {
                count++;
            }
        }
        int[] indexes = new int[count];
        int pos = 0;
        for (int i = 0 ; i != text.length() ; i++) {
            if (text.charAt(i) == ch) {
                System.out.println("Found '" + ch + "' at " + i);
                indexes[pos++] = i;
            }
        }
        return indexes;
    }