Reputation: 29
I was wondering how to iterate over a string and to check how many hi's come out
For example, if the string is "hihi" the count should output 2.
This is what I have so far
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);
}
Upvotes: 0
Views: 71
Reputation: 303
For compactness and readability, maybe:
int count = 0;
Matcher matcher = Pattern.compile(“hi”).matcher(string)
while (matcher.find()) {
count++;
}
This approach will work for any Regular Expression pattern, although it won’t be the most efficient.
Upvotes: 0
Reputation: 425013
Here's the easy way:
public static int countHi(String str) {
return split(str, -1).length - 1;
}
Note that you must pass -1
as the second parameter of split()
; without it, trailing blanks would be pruned from the result.
Upvotes: 0
Reputation: 201437
You compare instances (like String
) with .equals
(not ==
). However, here you can use ==
with String.charAt(int)
. Also, I would start with the second character and compare the character at the current index with i
and the previous index with h
. Like,
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;
}
Alternatively, compare the character at the current index with h
and the character at the next index with i
(but now you need to stop iterating a character earlier). Like,
public static int countHi(String str) {
int counter = 0;
for (int i = 0; i < str.length() - 1; i++) {
if (str.charAt(i) == 'h' && str.charAt(i + 1) == 'i') {
counter++;
}
}
return counter;
}
Upvotes: 1