Answers for "count number of characters"

1

how to count number of words in a string

String name = "Carmen is a fantastic play"; //arbitrary sentence
        
        int numWords = (name.split("\\s+")).length; //split string based on whitespace
                                                //split returns array - find legth of array
        
        System.out.println(numWords);
Posted by: Guest on June-06-2020
0

how to count number of characters in an array

int countChars(char *array[], int len)
{
    int total = 0, count = 0;


    for (int i = 0; i < len; i++)
    {
        if (array[i] != NULL)
        {
            while (*array[i] != '\0') {
                count++;
            }
            count++;
        }
        total += count;
    }

    return total;
}
Posted by: Guest on February-11-2020
1

count letters numbers and characters

public static String countLetter(String str){
    String abc=str;
    int a=0,b=0;
    while(str.length()>0){
        int i=0;
        String ch=str.substring(i,i+1);
        if(ch.matches(".*[a-zA-Z].*")){
            a++;
        }else if (ch.matches(".*[0-9].*")){
            b++;
        }
        str=str.substring(i+1);
    }
    return abc + " has "+a+" letters "+b+" digit 
          and "+(abc.length()-(a+b))+" other characters ";
      
      
OR+++++++++++++++++++++++++++++++++
      
      
  static void findSum(String str)
{
   int total= str.length();
   str = str.replaceAll("\\s", "");
   int num =0;
   int letter=0;
   int i=0;
   while(i<str.length()){
      char ch = str.charAt(i);
      // if current character is a digit
      if (Character.isDigit(ch))
         num ++;
         // if current character is an alphabet
      else {
         letter++;
      }
      i++;
   }
   System.out.println(letter + " letters -> "+num +
                      " numbers -> "+ (total-letter-num) + " other chars");
}
Posted by: Guest on January-22-2021

Code answers related to "count number of characters"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language