簡體   English   中英

計算給定字符串中字符的出現

[英]count occurrence of a character in a given string

我凍結了以下代碼以計算字符串中字符的出現:

public static void main(String[] args) {
    String source = "hello low how ale you";
    Scanner in = new Scanner(System.in);
    String temp = in.nextLine();
    char test = temp.toCharArray()[0];

    int fromIndex = 0;
    int occurences =0;

        while(fromIndex>-1)
        {
        fromIndex = source.indexOf(test, fromIndex);
        System.out.println("found at"+fromIndex);
        //if(fromIndex!=-1) occurences++;
        }
    System.out.println(occurences);
    }

如果將“ if(fromIndex!=-1)”行注釋掉,循環將無限運行! 如果取消注釋同一行,則循環將正確終止。 它奇怪地看到,循環的終止取決於變量fromIndex ,而不是變量的更新用occurences這是正在如果塊內更新。

為什么會這樣呢?

我認為您正在嘗試執行以下操作。

public class Solution {
    public static void main(String[] args) {
        String source = "hello low how ale you";
        char test = 'u';
        int fromIndex = 0;
        int occurrences = 0;
        int length = source.length();
        while (fromIndex < length) {
            int index = source.indexOf(test, fromIndex);
            if (index != -1) {
                occurrences++;
                fromIndex = index;
            }
            fromIndex++;
        }
        System.out.println(occurrences);
    }
}


一些解釋-

  1. 假設您需要在給定的字符串中找到'h',您將從0開始,因此fromIndex初始化將為0。
  2. 您從初始位置搜索到字符串的末尾。 這就是為什么在while循環中,您需要將條件設為fromIndex < length
  3. 現在,嘗試查找測試的發生。 如果有測試字符,則得到它的字符。 否則,您得-1。 將其存儲在index
  4. 現在,如果index不是-1,則將其分配給fromIndex 因為您現在將從該位置開始搜索。 從0開始不再。
  5. fromIndex增量。 無論index變量的值如何,都將完成此操作。

    現在分析您的代碼是否有錯誤。

如果您不嚴格要求使用類似代碼中的方法,建議您使用正則表達式。 您也將獲得更簡潔,更少的代碼。 試試下面的代碼片段,假設您有字符ch

char ch = 'o';
String input = "Hi there boys! Come on!";
String regex = ch + "";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);

ArrayList<String> matches = new ArrayList<String>();
while (m.find())
    matches.add(m.group());

System.out.println(matches.size());

fromIndex值在后續迭代中不會更改。 那就是無盡循環背后的原因。那是因為fromIndex會給出字符的確切索引。 在下一個循環中,將fromIndex增加1,這樣就可以解決問題。

while(fromIndex>-1)         
            {         
                fromIndex = source.indexOf(test, fromIndex+1);         
                System.out.println("found at"+fromIndex);         
                if(fromIndex!=-1) occurences++;         
                }          
            }       

希望這可以幫助。

暫無
暫無

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

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