在Java中,我们可以使用循环遍历字符串的每个字符,并使用条件语句判断是否为目标字符,然后累加出现次数。
以下是一个示例代码:
public class CharacterCount { public static void main(String[] args) { String str = "Hello World"; char targetChar = 'o'; int count = 0; // 遍历字符串的每个字符 for (int i = 0; i < str.length(); i++) { // 判断是否为目标字符 if (str.charAt(i) == targetChar) { count++; } } System.out.println("目标字符出现的次数:" + count); } }
上述代码中,我们定义了一个字符串str
和目标字符targetChar
,然后通过遍历字符串的每个字符,判断是否为目标字符并累加出现次数。最后输出目标字符出现的次数。
在这个示例中,字符'o'
在字符串"Hello World"
中出现了两次,所以输出结果为2
。