簡體   English   中英

如何解決Java編程語言中的索引

[英]how to solve the indexing in java programming language

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時搜索給定的letter。 方法將返回它的索引,但是主要問題是字符串中有多個相同的字母,因此它將返回第一個。 以及如何檢測第二個字母或如何區分第二個相同的字母並顯示為索引,例如:

的indexOf( “kingJoker”, 'K');

在kingjoker字符串中,我們有兩個k字母,該方法找不到第二個k索引,因此就是問題所在。

  • 將方法的返回類型更改為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;
}

要檢測多個字母,建議您將每個索引存儲在List<Integer> 您可以使用以下內容(由smac89的答案提供 ):

public static List<Integer> indexOf(String text, char index) {
    return IntStream.range(0, text.length())
                    .filter(i -> s.charAt(i) == index)
                    .boxed()
                    .collect(Collectors.toList());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM