![](/img/trans.png)
[英]count occurrence of a character in a given string using one for loop with java
[英]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);
}
}
一些解釋-
fromIndex
初始化將為0。 fromIndex < length
。 index
。 index
不是-1,則將其分配給fromIndex
。 因為您現在將從該位置開始搜索。 從0開始不再。 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.