考虑:
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
Run Code Online (Sandbox Code Playgroud)
for (String item : someList) {
System.out.println(item);
}
Run Code Online (Sandbox Code Playgroud)
如果for不使用for each语法,等效循环会是什么样的?
我有字符串
a.b.c.d
Run Code Online (Sandbox Code Playgroud)
我想计算'.'的出现次数.以惯用的方式,最好是单线.
(以前我把这个约束表达为"没有循环",如果你想知道为什么每个人都试图回答而不使用循环).
为什么以下算法不会停止?(str是我正在搜索的字符串,findStr是我想要查找的字符串)
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while (lastIndex != -1) {
lastIndex = str.indexOf(findStr,lastIndex);
if( lastIndex != -1)
count++;
lastIndex += findStr.length();
}
System.out.println(count);
Run Code Online (Sandbox Code Playgroud) 到目前为止,这是我尝试过的:
public class CharacterCounter {
public static void main(String[] args){
String string = "sashimi";
int count = 0;
for(int i =0; i < string.length(); i++){
if(string.charAt(i) == 'i'){
count++;
}
}
System.out.println("The number of letter i is " + count);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
The number of letter i is 2
Run Code Online (Sandbox Code Playgroud)
但我想做的是,该程序应该计算最常出现的字符.
例如,这里的字符串是SASHIMI,输出应该是:
the number of letter S is 2
the number of letter I is 2
Run Code Online (Sandbox Code Playgroud)
我遇到了这个问题.我需要你的帮助.谢谢.