Java 程序查找字符串中字符的所有出现次数

编写一个 Java 程序,通过示例查找字符串中字符的所有出现次数。在此 java return all Character Occurrences 示例中,我们使用 While 循环从头到尾迭代 facStr。在其中,我们使用 String charAt (facStr.charAt(i)) 函数读取每个索引位置的字符。

接下来,我们将 acStr.charAt(i) 字符与 ch 字符进行比较,以检查它们是否相等。如果为真,我们将打印该字符及其位置(不是索引位置)。如果您想要提取索引位置,请将 i + 1 替换为 i。

import java.util.Scanner;

public class FindAllCharOccurence1 {
	private static Scanner sc;
	public static void main(String[] args) {
		String facStr;
		char ch;
		int i = 0;
		
		sc= new Scanner(System.in);

		System.out.print("\nPlease Enter any String =  ");
		facStr = sc.nextLine();
		
		System.out.print("\nEnter the Character to Find =  ");
		ch = sc.next().charAt(0);
		
		while(i < facStr.length())
		{
			if(facStr.charAt(i) ==  ch) {
				System.out.format("\n %c Found at Position %d ", ch, i + 1);
			}
			i++;
		}
	}
}

Java 字符串中所有字符出现次数的输出

Please Enter any String =  hello world

Enter the Character to Find =  l

 l Found at Position 3 
 l Found at Position 4 
 l Found at Position 10 

使用 For 循环查找字符串中字符所有出现次数的 Java 程序

import java.util.Scanner;

public class FindAllCharOccurence2 {
	private static Scanner sc;
	public static void main(String[] args) {
		String facStr;
		char ch;

		sc= new Scanner(System.in);

		System.out.print("\nPlease Enter any String =  ");
		facStr = sc.nextLine();
		
		System.out.print("\nEnter the Character to Find =  ");
		ch = sc.next().charAt(0);
		
		for(int i = 0; i < facStr.length(); i++)
		{
			if(facStr.charAt(i) ==  ch) {
				System.out.format("\n %c Found at Position %d ", ch, i );
			}
		}
	}
}
Java Program to Find All Occurrences of a Character in a String

这是另一个 Java 示例,用于返回给定字符串中所有字符的出现次数。在这里,我们使用 Java 函数分离了逻辑。

import java.util.Scanner;

public class FindAllCharOccurence3 {
	private static Scanner sc;
	public static void main(String[] args) {
		String facStr;
		char ch;

		sc= new Scanner(System.in);

		System.out.print("\nPlease Enter any String =  ");
		facStr = sc.nextLine();
		
		System.out.print("\nEnter the Character to Find =  ");
		ch = sc.next().charAt(0);
		
		FindAllCharacterOccurences(facStr, ch);	
	}
	
	public static void FindAllCharacterOccurences(String facStr, char ch) {
		for(int i = 0; i < facStr.length(); i++)
		{
			if(facStr.charAt(i) ==  ch) {
				System.out.format("\n %c Found at Position %d ", ch, i);
			}
		}
	}
}
Please Enter any String =  java programming language

Enter the Character to Find =  a

 a Found at Position 1 
 a Found at Position 3 
 a Found at Position 10 
 a Found at Position 18 
 a Found at Position 22 

请参考以下字符串程序。

  1. 计算字符串中字符的总出现次数
  2. 字符串中的第一个字符出现次数
  3. 替换字符串中某个字符的首次出现
  4. 删除字符串中某个字符的首次出现
  5. 字符串中的最后一个字符出现次数
  6. 替换字符串中某个字符的最后一次出现
  7. 删除字符串中的最后一个字符出现次数
  8. 字符串中的第一个和最后一个字符
  9. 删除字符串中的第一个和最后一个字符
  10. 字符串中出现次数最多的字符
  11. 字符串中出现次数最少的字符
  12. 字符串中每个字符的频率
  13. 删除字符串中某个字符的所有出现