下面是一个用Java编写的计算字符串中某个元素出现次数的示例代码:
public class StringOccurrenceCount {
public static int countOccurrences(String inputString, char targetChar) {
int count = 0;
for (int i = 0; i < inputString.length(); i++) {
if (inputString.charAt(i) == targetChar) {
count++;
}
}
return count;
}
public static void main(String[] args) {
String inputString = "Hello, world!";
char targetChar = 'o';
int occurrences = countOccurrences(inputString, targetChar);
System.out.println("The character '" + targetChar + "' occurs " + occurrences + " times in the string.");
}
}
在上述代码中,我们定义了一个名为countOccurrences
的静态方法,它接受一个字符串和一个目标字符作为参数,并返回目标字符在字符串中出现的次数。
在countOccurrences
方法中,我们使用一个循环遍历字符串中的每个字符。如果当前字符与目标字符相同,则将计数器增加1。
在main
方法中,我们定义了一个示例输入字符串"Hello, world!"
和目标字符'o'
。然后,我们调用countOccurrences
方法来计算目标字符在输入字符串中出现的次数,并将结果打印到控制台。
执行上述代码将输出:
The character 'o' occurs 2 times in the string.