Write a Java program to count the letters, spaces, numbers and other characters of an input string


Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. import java.util.Scanner;
  2. public class Javaexcercise {
  3.  
  4. public static void main(String[] args) {
  5. String test = "@TechStudy.org 123456";
  6. count(test);
  7.  
  8. }
  9. public static void count(String x){
  10. char[] ch = x.toCharArray();
  11. int letter = 0;
  12. int space = 0;
  13. int num = 0;
  14. int otherchat = 0;
  15. for(int i = 0; i < x.length(); i++){
  16. if(Character.isLetter(ch[i])){
  17. letter ++ ;
  18. }
  19. else if(Character.isDigit(ch[i])){
  20. num ++ ;
  21. }
  22. else if(Character.isSpaceChar(ch[i])){
  23. space ++ ;
  24. }
  25. else{
  26. otherchat ++;
  27. }
  28. }
  29. System.out.println("The string is : @TechStudy.org 123456");
  30. System.out.println("letter: " + letter);
  31. System.out.println("space: " + space);
  32. System.out.println("number: " + num);
  33. System.out.println("other: " + otherchat);
  34. }
  35. }

Result

java techstudy.org

     





Related Topics




Popular Posts