//program to take a string and also take a praticular char from a user which they want to count---
PROGRAM CODE---
import java.util.Scanner;class CountChar{ public static void main(String a[]){ int count=0;
Scanner s = new Scanner(System.in);
System.out.println("enter a string"); String st = new String(s.nextLine());
System.out.println("enter a character which you want to count");
char ch = s.next().charAt(0); for(int i =0;i<=st.length()-1;i++){ if(st.charAt(i)==ch){ count=count+1;}
}System.out.println("given character counting of given string is"+count);}}
OUTPUT OF ABOVE PROGRAM
ABOUT:
- IN THIS PROGRAM WE TAKE A STRING FROM USER BY USE SCANNER CLASS.
- ALSO TAKE A PARTICULAR CHARACTER FROM USER BY USING (charAt) METHOD.
- LOOP WILL EXECUTE UNTIL THE END OF THE STRING.
- IN LOOP, WE COMPARE CHARACTER OF A LOOP POSITION ,,IF THIS CHARACTER EQUAL TO USER CHARACTER ,SO COUNT INCREMENT BY ONE...
- IN THE END , PRINT THE COUNT ....(WHICH TELL HOW MANY TIMES THAT PARTICULAR CHARACTER PRESENT IN GIVEN STRING...)
Comments
Post a Comment