Java在sting中查找特定的字母
我想知道如何迭代一个字符串,并检查有多少hi出现 例如,如果字符串为“hihi”,则计数应输出2 这就是我目前所拥有的Java在sting中查找特定的字母,java,string,Java,String,我想知道如何迭代一个字符串,并检查有多少hi出现 例如,如果字符串为“hihi”,则计数应输出2 这就是我目前所拥有的 public static int countHi(String str) { int counter = 0; for (int i = 0; i < str.length(); i++) { if (str.substring(i, i + 1) == "h") { if (str.subst
public static int countHi(String str) {
int counter = 0;
for (int i = 0; i < str.length(); i++) {
if (str.substring(i, i + 1) == "h") {
if (str.substring(i, i + 1) == "i") {
counter = counter + 1;
}
}
}
return counter;
}
public static void main(String[] args) {
String str = "hihi";
int i = countHi(str);
System.out.println("number of hi = " + i);
}
publicstaticintcounthi(stringstr){
int计数器=0;
对于(int i=0;i
您将实例(如字符串
)与.equals
(而不是=
)进行比较。但是,这里您可以将==
与一起使用。另外,我将从第二个字符开始,将当前索引中的字符与I
进行比较,并将上一个索引中的字符与h
进行比较。像
public static int countHi(String str) {
int counter = 0;
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i - 1) == 'h' && str.charAt(i) == 'i') {
counter++;
}
}
return counter;
}
以下是简单的方法:
public static int countHi(String str) {
return split(str, -1).length - 1;
}
请注意,必须将
-1
作为split()
的第二个参数传递;如果没有它,后面的空格将从结果中删除。为了紧凑性和可读性,可能:
int count = 0;
Matcher matcher = Pattern.compile(“hi”).matcher(string)
while (matcher.find()) {
count++;
}
这种方法适用于任何正则表达式模式,尽管它不是最有效的。有紧凑型,还有:)是的,但紧凑型只有在我的书中简单明了的时候才是好的。剩下的只是智力上的胡闹。现在你们两个下属都在看同一个字母,从i到i+1。此外,您还应该确保循环转到str.length()-2,以便实现不会抛出错误。
int count = 0;
Matcher matcher = Pattern.compile(“hi”).matcher(string)
while (matcher.find()) {
count++;
}