Tag: java string program

  • Java Program to Sort String in an Alphabetical order

    In this another java tutorial lesson on Java alphabetical sort, we will learn how to sort strings in an order of alphabets.
    Let’s begin.

    Program explanation for arranging string in alphabetic order in java:

    First, we will take the user input for how many strings to enter? with the help scanner class. Then ask the user to input all the strings one by one and get them with help of for loop.

    Then to sort strings that are stored in a string array, we compare the first alphabet of each array to display them in alphabetic order in java with the help of the compareTo() function. If the first alphabet is the same it will compare the second alphabet and so on.


    Java Program to Sort String in an Alphabetical Order

    //java sort string
    
    import java.util.Scanner;
    
    public class JavaSortString
    {
      public static void main(String[] args)
      {
        int lenStr;
        String temp;
    
        Scanner scan = new Scanner(System.in);
    
        //number of strings
        System.out.print("How many Strings would you like to enter? ");
        lenStr = scan.nextInt();
    
        String str[] = new String[lenStr];
    
        Scanner scan2 = new Scanner(System.in);
    
        //getting all the strings
        System.out.println("Enter the " + lenStr + " Strings: ");
        for (int i = 0; i < lenStr; i++)
        {
          str[i] = scan2.nextLine();
        }
    
        scan.close();
        scan2.close();
    
        //Sorting strings with compareTo()
        for (int i = 0; i < lenStr; i++)
        {
          for (int j = i + 1; j < lenStr; j++)
          {
            if (str[i].compareTo(str[j]) > 0)
            {
              temp = str[i];
              str[i] = str[j];
              str[j] = temp;
            }
          }
        }
    
        //Print the sorted strings
        System.out.print("Strings sorted n alphabetical order: ");
        for (int i = 0; i <= lenStr - 1; i++)
        {
          System.out.print(str[i] + ", ");
        }
      }
    }

    Output: After executing the above program, the following output will be displayed.

    Sort String Alphabetically in java

  • Java Program to Find the Number of Vowels and Consonants in a String

    The program to find the number of vowels and consonants present in a String in java is simple. It checks each of the characters in strings and compares it with vowels (i.e. a, e, i, o, u).

    When the program finds the character equals to vowel then it increases the vow integer else cons integer increases. And at last, the result is displayed.

    You may also take the user input instead of declaring the String in a Program. Following the below to take a user input.


    Java Program to Find the Number of Vowels and Consonants in a String

     //number of vowels and consonants in a string 
    
     public class CountVowelConsonants
     {
       public static void main(String[] args)
       {
         String str = "Learning To Code";
         int vow = 0, cons = 0;
         str = str.toLowerCase();
    
         for (int i = 0; i < str.length(); ++i)
         {
           char ch = str.charAt(i);
           if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
           {
             ++vow;
           }
           else if ((ch >= 'a' && ch <= 'z'))
           {
             ++cons;
           }
         }
    
         System.out.println("Number of Vowels : " + vow);
         System.out.println("Number of Consonants: " + cons);
       }
     }

    Output:

    Number of Vowels : 6
    Number of Consonants: 8


  • Java Program to Count Total Character in a String

    In this tutorial, we will see how to Count Total Characters in a String in java.

    The program below counts the number of letters present in the sentence (String) and displays the total character present in number.

    The program checks for spaces present in the Strings and if gets space while checking each character then it will skip the spaces, charAt() function is used in the following java program.

    Although if you want to know about the String and loop that are used in the program below. you may click the link below:

    We will see two Example:

    1. Where the String is already defined in the program.
    2. Where the string is taken as an input from the user.


    1. Program to Count Total Character in a String in Java

     //count total character in a string
    
     public class CountCharString
     {    
      public static void main(String[] args) 
      {    
        String str = "I am learning java";    
        int count = 0;  
          
        //counting String
        for(int i = 0; i < str.length(); i++) 
        {    
          if(str.charAt(i) != ' ')    
              count++;    
        }    
              
        //Displays the total character, space exclused    
        System.out.println("Total character in a given string: " + count);    
      }    
     }

    Output:

    Total character in a given string: 15


    2. Program to Count Total Character in a String in Java

    We will see the example where we will get the String from the user inputs in the program as shown below:

    //count total character in a string (user inputs)
     
     import java.util.Scanner;
    
     public class CountCharString
     {    
       public static void main(String[] args) 
       {    
         String str;    
         int count = 0;  
         
         Scanner in = new Scanner(System.in);
      
          //User Input
          System.out.println("Enter a string: ");
          str = in.nextLine();
                 
          //Excluding Space  
          for(int i = 0; i < str.length(); i++) 
          {    
             if(str.charAt(i) != ' ')    
                count++;    
          }    
                 
          //Displays the total character, space exclused    
          System.out.println("Total character in a entered string: " + count);    
         }    
     }

    Output:

    Enter a string:
    I am learning java
    Total character in a entered string: 15


  • Java Program to Find the Frequency of a Character

    In this tutorial, we will write a program to calculate the frequency of Characters present in a String in java.

    Frequency refers to the number of times that have occurred. In this program, we will count how many times each character is repeated in a String and display the result for each word’s frequency.

    The program splits each word with space count present after every word, toCharArray() function is used in the following java program.

    Although if you want to know about the String and loop that are used in the program below. you may click the link below:

    We will see two examples:

    1. Where the String is already defined in the program.
    2. Where the string is taken as an input from the user.


    1. Program to find the frequency of Words in Java

    //find a frequency of a character 
    
    public class FrequencyOfCharacter
    {
      public static void main(String[] args)
      {
        int i, j;
        String str = "Beautiful Beach";
        int[] frequency = new int[str.length()];
    
        char string[] = str.toCharArray();
    
        for (i = 0; i < str.length(); i++)
        {
          frequency[i] = 1;
          for (j = i + 1; j < str.length(); j++)
          {
            if (string[i] == string[j])
            {
              frequency[i]++;
    
             	//Set string[j] to 0  
              string[j] = '0';
            }
          }
        }
    
        //Displays the characters with their frequency    
        System.out.println("Following Lists the characters and their frequency:");
        for (i = 0; i < frequency.length; i++)
        {
          if (string[i] != ' ' && string[i] != '0')
            System.out.println(string[i] + "->" + frequency[i]);
        }
      }
    }

    Output:

    Following Lists the characters and their frequency:
    B->2
    e->2
    a->2
    u->2
    t->1
    i->1
    f->1
    l->1
    c->1
    h->1

    2. Program to find the frequency of Words in Java, user’s input

    //find a frequency of a character 
    
    import java.util.Scanner;
    
    public class FrequencyOfCharacter
    {
      public static void main(String[] args)
      {
        int i, j;
        String str;
        Scanner sc = new Scanner(System.in);
    
        //User Input
        System.out.println("Enter a string: ");
        str = sc.nextLine();
    
        int[] frequency = new int[str.length()];
    
        char string[] = str.toCharArray();
    
        for (i = 0; i < str.length(); i++)
        {
          frequency[i] = 1;
          for (j = i + 1; j < str.length(); j++)
          {
            if (string[i] == string[j])
            {
              frequency[i]++;
    
              //Set string[j] to 0  
              string[j] = '0';
            }
          }
        }
    
        //Displays the characters with their frequency    
        System.out.println("Following Lists the entered characters and their frequency:");
        for (i = 0; i < frequency.length; i++)
        {
          if (string[i] != ' ' && string[i] != '0')
            System.out.println(string[i] + "->" + frequency[i]);
        }
      }
    }

    Output:

    Enter a string: 
    Beautiful Beach
    Following Lists the characters and their frequency:
    B->2
    e->2
    a->2
    u->2
    t->1
    i->1
    f->1
    l->1
    c->1
    h->1

  • Java Program to Find a Frequency of Words

    In this tutorial, we will see how to calculate the frequency of words present in a String in java.

    Frequency refers to the number of times that have occurred. In this program, we will count how many time each word are repeated and display the result for each word’s frequency.

    The program splits each word with space count present after every word, split() and equals() functions are used in the following java program.


    Java Program to Find a Frequency of Words

    //find a frequency of words
    
     public class RepeatedWord
     {
     
      public static void main(String[] args)
      {
          String input="Welcome to java java Simle2code to java";  //String
          
          String[] words = input.split(" ");  //Split the word from String
          int wc = 1;    //word count initiated
          
          for(int i=0; i < words.length;i++)  
          {
            for(int j = i+1; j < words.length;j++) 
            {
             if(words[i].equals(words[j]))  //Checking for both strings are equal
             {
               wc = wc+1;    //if equal increment the count
               words[j]="0"; //Replace repeated words by zero
             }
            }
            if(words[i]!="0")
            System.out.println(words[i]+"--"+wc); //Display
            wc=1;
            
          }  
      }
    }

    Output:

    Welcome--1
    to--2
    java--3
    Simle2code--1


  • Java Program to Count the Number of Words Present in a text file

    In this tutorial, we will see the example of how to count the number of words present in a text file in java.

    First, create a text file with any name you like. In this example, inputInfo.txt is the file name. Then insert some sentences in that text file. The following java code will count the number of words present in that file.

    Before we start, it is important that you have an idea of the following, as this program uses them.


    Java Program to count the number of words present in a file

    //count the number of words present in a text file 
    
     import java.io.BufferedReader;  
     import java.io.FileReader;  
       
     public class CountNoOfWords
     {  
        public static void main(String[] args) throws Exception 
        {  
        String str;  
        int count = 0;  
    
        //file in read mode  
        FileReader f = new FileReader("inputInfo.txt ");  
        BufferedReader br = new BufferedReader(f);  
    
      
        while((str= br.readLine()) != null) 
        {  
          //Splits into words  
          String words[] = str.split(""); 
    
          //Counts each word  
          count = count + words.length;  
    
        }  
    
        System.out.println("Number of words present in given file: " + count);  
        br.close();  
        }  
     }

    Output:

    Number of words present in given file: 72


  • Java Program to Check if the String is empty or not

    In this tutorial, we will write a java program to check whether the string is empty or not.

    The strings are defined in the program and it is passed to the method as an argument. After checking for null and empty (built-in empty() function is used), a true or false value is returned accordingly. And finally displays the result.

    The condition checking in this program is performed with the help of if..else statement:


    Check if the String is empty or not in Java

    //check if the string is empty or not in java
    
     public class CheckForEmpty
     {
         public static void main(String[] args) 
         {
            String string1 = "Simple2Code";
            String string2 = "";
            
            if(checkEmpty(string1 ))
                System.out.println("string1 is empty.");
            else
                System.out.println("string1 is not empty.");
                
            if(checkEmpty(string2 ))
                System.out.println("string2 is empty.");
            else
                System.out.println("string2 is not empty.");
         }
         
         public static boolean checkEmpty(String str) 
         {
            if(str != null && !str.isEmpty())
            {
              return false;
            }
            else
            {
              return true;
            }
         }
     }

    Output:

    string1 is not empty.
    string2 is empty.


  • Java Program for user String Input

    It is a simple demonstration to show how to take a string as an input from the user.

    The only thing you need to be concerned about is the data type that you declare in the program that is the String data type as shown below in the program.


    How to take user Input as String in java

     //user String input in java
    
     import java.util.Scanner;
     public class UserInput
     {
        public static void main(String []args)
        {
           String str;
           Scanner in = new Scanner(System.in);
      
          //Get input String
          System.out.println("Enter a string: ");
          str = in.nextLine();
          
          System.out.println("Entered String is: "+str);
         } 
     }

    Output:

    Enter a string:
    I am Coding right now.
    Entered String is: I am Coding right now.


  • Java Program to Count Letters in a String

    In this tutorial to Count Letters in a String in java, we will see two examples to count the number of letters present in a String in Java.

    • The first one, where the String is already defined in a program.
    • The second one, where the String is taken as input from the user

    Both the program uses for loop and if statement to count the letters so if you do not know about them, click the link below.


    1. Java Program to Count the Letters in a String.

     //count letters in a string 
    
     public class CountLetters
     {
        public static void main(String []args)
        {
           String str = "ab5gh6d"; //given String
           int count = 0;
           
           System.out.println("Given String is: "+str);
     
           for (int i = 0; i < str.length(); i++) 
           {
              if (Character.isLetter(str.charAt(i)))
              {
                count++;
              }
           }
           System.out.println("Number of Letters in a given string: "+count);
        }
     }

    Output:

    Given String is: ab5gh6d
    Number of Letters in a given string: 5


    2. Java Program to Count the Letters in a String (user’s input)

     //count letters in a string (user inputs)
     
     import java.util.Scanner;
    
     public class CountLetters
     {
      public static void main(String []args)
      {
        String str;
        int count = 0;
        
        Scanner sc = new Scanner(System.in);
    
       //Get input String
        System.out.println("Enter a string: ");
        str = sc.nextLine();
        
        System.out.println("Entered String is: "+str);
    
        for (int i = 0; i < str.length(); i++) 
        {
          if (Character.isLetter(str.charAt(i)))
          {
            count++;
          }
        }
        System.out.println("Number of Letters Present in a String are: "+count);
      }
     }

    Output:

    Enter a string: 45ab6gh

    Entered String is: 45ab6gh
    Number of Letters Present in a String are: 4


  • Java Program – How to Reverse Sentences in String

    Reverse a sentence word by word in java:

    Reversing a string in java is easy. Here we reverse the sentence of words from back to front rather than reversing each word.

    Example: Let us consider a string “I am a code” and the output will be “code a am I“.

    Explanation:
    First, we take a String from user input with the help of a Scanner class. Then we again with help of split() function we split the input string into separate words that is String[] wordsRev = str.split("\s");.

    Take an empty string to store the reverse sentence. Then the iteration of for loop starts for i equal to the length of the words present in a string. Then the split words are store in the result String from backward inside the for loop.

    For loop will continue until i is less than or equal to zero. Integer i will decrease by 1 at every iteration. Since we take the length from backward we decrease the value of i.
    At last, print the result String(resultString).


    Java Program to Reverse a Sentence Word by Word

    import java.util.Scanner;
     
    public class ReverseTheString 
    {
        public static void main(String[] args) 
        {
            Scanner sc = new Scanner(System.in);
            String str;
            
            System.out.println("Enter the String :");
            str = sc.nextLine();
             
            //String outputString = reverseTheSentence(str);
             
            String[] wordsRev = str.split("\\s");
             
            String resultString = "";
             
            for (int i = wordsRev.length-1; i >= 0; i--)
            {
                resultString = resultString + wordsRev[i] + " ";
            }
             
            System.out.println("Output String : "+resultString);
             
            sc.close();
        }
    }

    The output of reversing the words in a sentence n java: