Java 使用CharAt和length方法
我正在尝试为StringAmount类编写一个方法 该方法是int count(String s,char ch),它计算字符ch在字符串s中出现的次数,并返回该计数。Java 使用CharAt和length方法,java,string,Java,String,我正在尝试为StringAmount类编写一个方法 该方法是int count(String s,char ch),它计算字符ch在字符串s中出现的次数,并返回该计数。public int count(String s,char ch) public int count( String s, char ch ) { int occurrences = 0; for ( int i = 0; i < s.length(); ++i ) if ( s.char
public int count(String s,char ch)
public int count( String s, char ch )
{
int occurrences = 0;
for ( int i = 0; i < s.length(); ++i )
if ( s.charAt(i) == ch )
++occurrences;
return occurrences;
}
{
int=0;
对于(int i=0;i
在进入for循环之前,可以将s.length()存储在变量中,这样就不会在每次迭代时调用函数。这是一个~非常~小的优化,但它是一个优化。你可以做一些简单的事情,比如-
public int count(String s, char ch)
{
int count = 0;
for(int i=0;i <s.length();i++)
{
if(s.charAt(i) == ch)
{
count++;
}
}
return count;
}
public int count(字符串s,字符ch)
{
整数计数=0;
对于(int i=0;我想你对这个方法有一个具体的问题吗?那么写一些代码,告诉我们你做了什么。我投票结束这个问题,因为它要求写代码。如果我调用:count(“this”,“t”)
-你不能假设s
不包含“is”更不用说用户想要使用String类的charAt()和length()方法,而您两种方法都没有使用。
private int count(String s, char ch) {
int index = s.indexOf(ch);
int count = 0;
while (index != -1) {
count++;
s = s.substring(index + 1);
index = s.indexOf(ch);
}
System.out.println("No of " + ch +" in the input is : " + count);
return count;
}