[英]How to count a specific character within a string using a while Loop - Java
[英]How to count if a specific string matches while iterating through a loop in java?
這是我過去無法及時完成的以前的家庭作業。 我是一個新的程序員,正努力使用CharacterSearch程序的這種方法。 我陷入了要為if語句使用哪種布爾邏輯的問題,以及如何使用預定義的字符變量在短語中查找匹配項。 測試示例為:character =“ x”,短語=“ Xerox”。 X和x不同。 預期的輸出應為count =1。編輯:應在不使用數組或列表的情況下解決此問題。
/**
* Counts and returns the number of times the letter for this class
* occurs in the phrase. The class is case sensitive.
*/
public int letterCount(String phrase)
{
Scanner jf = new Scanner(phrase);
count = 0;
for (int i = phrase.length(); i > 0; i--)
{
jf.findInLine(character);
if(jf.hasNext())
{
count++;
jf.next();
}
}
return count;
}
你去了:
/**
* Counts and returns the number of times the letter for this class
* occurs in the phrase. The class is case sensitive.
*/
public int letterCount(String phrase)
{
int count = 0;
// for every character in phrase ...
for (int i = 0; i < phrase.length(); i++)
{
// ... if it is the right one ...
if(phrase.charAt(i) == character)
{
// ... increment the counter
count++;
}
}
return count;
}
您不需要任何掃描儀,並且代碼非常簡單,易讀且易於理解。
計算字符串中字符出現次數的簡單方法幾乎與之重復
我不能發表評論,因為我的代表人數太少,但我想給你一個可以使用的解決方案。
public int letterCount(String phrase)
{
count = 0;
for (int i = 0 ; i < phrase.length(); i++)
{
String myLetter = phrase.substring(i, i + 1);
if (myLetter.equals(character))
{
count++;
}
}
return count;
}
我發現自己在錯誤的方向上進行迭代,但是更重要的是,我沒有聲明一個子字符串來檢查我的字符是否匹配短語中的各個字母。
將String的子字符串與compare()一起使用。
public int letterCount(String phrase, String match)
{
int count = 0;
for(int i=0;i<phrase.length()-1;i++){ //-1 avoid out-of-bound exception
String letter = phrase.substring(i, i+1);
if(letter.compareTo(match) == 0){
count++;
}
}
return count;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.