编写一个 Java 程序,使用示例计算字符串中字符的总出现次数。在此字符串字符出现次数示例中,我们使用 While 循环从头到尾迭代 calStr 字符串。
在循环中,我们将每个 calStr 字符串字母 (charAt()) 与 ch 进行比较。如果它们相等,我们将 charCount 加一。最后,我们将 charCount 作为输出打印出来。
import java.util.Scanner;
public class CountAllCharOccurence1 {
private static Scanner sc;
public static void main(String[] args) {
String calStr;
char ch;
int i = 0, charCount = 0;
sc= new Scanner(System.in);
System.out.print("\nPlease Enter String to Count all Char Occurrence = ");
calStr = sc.nextLine();
System.out.print("\nEnter the Character to Find = ");
ch = sc.next().charAt(0);
while(i < calStr.length())
{
if(calStr.charAt(i) == ch) {
charCount++;
}
i++;
}
System.out.format("\nTotal Number of time %c has found = %d ",
ch, charCount);
}
}

Java 程序使用 for 循环计算字符串中字符的总出现次数
此字符总出现次数示例与上面相同。在此 Java 示例中,我们用 For 循环 替换了 While 循环。
import java.util.Scanner;
public class CntAllChOcc32 {
private static Scanner sc;
public static void main(String[] args) {
String calStr;
char ch;
int i, charCount = 0;
sc= new Scanner(System.in);
System.out.print("\nPlease Enter String = ");
calStr = sc.nextLine();
System.out.print("\nEnter the Character to Find = ");
ch = sc.next().charAt(0);
for(i = 0; i < calStr.length(); i++)
{
if(calStr.charAt(i) == ch) {
charCount++;
}
}
System.out.format("\nTotal Number of time %c has found = %d ",
ch, charCount);
}
}
Please Enter String = hello world
Enter the Character to Find = l
Total Number of time l has found = 3
此程序使用函数计算字符串中字符的总出现次数。在这里,我们创建了一个 CountAllCharOcc 函数,该函数返回字符计数。
import java.util.Scanner;
public class CntAllChOcc3 {
private static Scanner sc;
public static void main(String[] args) {
sc= new Scanner(System.in);
System.out.print("\nPlease Enter Text = ");
String calStr = sc.nextLine();
System.out.print("\nEnter the Letter to Find = ");
char ch = sc.next().charAt(0);
int charCount = CntAllCharOcc(calStr, ch);
System.out.format("\nTotal Number of time %c has found = %d ", ch, charCount);
}
public static int CntAllCharOcc(String calStr, char ch) {
int i, charCount = 0;
for(i = 0; i < calStr.length(); i++)
{
if(calStr.charAt(i) == ch) {
charCount++;
}
}
return charCount;
}
}
Please Enter Text = tutorial gateway
Enter the letter to Find = t
Total Number of time t has found = 3
请参考以下字符串程序。
- 查找字符串中所有字符的出现次数
- 字符串中第一个字符的出现次数
- 替换字符串中某个字符的首次出现
- 删除字符串中某个字符的首次出现
- 字符串中最后一个字符的出现次数
- 替换字符串中某个字符的最后一次出现
- 删除字符串中最后一个字符的出现次数
- 字符串中的第一个和最后一个字符
- 删除字符串中的第一个和最后一个字符
- 字符串中出现次数最多的字符
- 字符串中出现次数最少的字符
- 字符串中每个字符的频率
- 删除字符串中某个字符的所有出现