Tag: java string program

  • Java Program to Count the Number of Words present in a String using HashMap

    Counting words in java using HashMap:

    This program demonstrates the use of HashMap in java to count the number of words.
    First, we take the string from user input using Scanner class and store it in a string “str“. After then, using the java split() function for spaces(” “) we separate the words from spaces to count the words.

    Then we declare the HashMap(which is a part of java’s collection that stores data in (Key, value) pairs). The Key in this program is String and the Value in an Integer. Then we iterate using for loop and inside for loop, we have if-else statement and if HashMap (Hmap) contains a key we add the object to the Hmap. And the count is set to the current position and with the increment by 1. Under Else, the counter is set to 1.

    The for loop will continue until the length of the split() – 1.
    Then we display the count of a number of words stored in an Hmap.


    Java Program to Count the Number of Words present in a String using HashMap.

    import java.util.Scanner;
    import java.util.HashMap;
    
    public class FinalCountWords 
    {
    
     public static void main(String[] args) 
     {
        Scanner in = new Scanner(System.in);
        String str;
    	
        System.out.println("Enter a string: ");
        str= in.nextLine();
       
        String[] splitFn = str.split(" ");
    	
        HashMap<String,Integer> Hmap = new HashMap<String,Integer>();
    	
        for (int i=0; i < splitFn.length-1; i++)
        {
          if (Hmap.containsKey(splitFn[i])) 
          {
    	int count = Hmap.get(splitFn[i]);
    	Hmap.put(splitFn[i], count+1);
          }
          else 
          {
            Hmap.put(splitFn[i], 1);
          }
        }
       System.out.println(Hmap);
     }
    }

    The Output of counting the words using HashMap in java:

    count words using hashmap in java

  • Java Program to Remove all White Spaces from a String

    White Space removal program in java:
    In this post, we will learn how to remove white spaces from a string in java. We will learn the two ways to remove white spaces in java.

    First by using in-built methods called replaceAll() and second without the use of in-built methods (for loop).


    1. Java program to remove white spaces in a string using replaceAll().

    This is the easiest method to remove spaces from a string in java. replaceAll() takes in two parameters, one is the string to be replaced and another one is the string to be replaced with.

    In this example, we will take the string from the user input with the help of a scanner class and as a parameter, we pass “\\s” that will be replaced with “”.

    Example Program:

    import java.util.Scanner;
    
    public class WhiteSpaceRemoval
    {
      public static void main(String[] args)
      {
        Scanner sc = new Scanner(System.in);
    
        System.out.println("Enter the string with spaces");
    
        String str1 = sc.nextLine();
    
        //relaceAll()
        String str2 = str1.replaceAll("\\s", "");
    
        System.out.println(str2);
      }
    }

    The output of removing spaces from a string in java:


    2. Java program to remove white spaces in a string using for loop

    This is another method to remove white spaces. Although the above approach is recommended when it comes to creating a real-time application. This is mostly for interview programs asked.

    In this method, we take the user input for string and convert them to character Array(charArray) and check those characters for white spaces by running it into the iteration. for loop will iterate until the length of the entered string.

    Example Program:

    import java.util.Scanner;
    
    public class WhiteSpaceRemoval
    {
      public static void main(String[] args)
      {
        Scanner sc = new Scanner(System.in);
    
        System.out.println("Enter the string with spaces");
        String inputString = sc.nextLine();
    
        char[] charArray = inputString.toCharArray();
    
        String resultString = "";
    
        for (int i = 0; i < charArray.length; i++)
        {
          if ((charArray[i] != ' ') && (charArray[i] != '\t'))
          {
            resultString = resultString + charArray[i];
          }
        }
    
        System.out.println("Result String without spaces: " + stringWithoutSpaces);
    
        sc.close();
      }
    }

    The output of removing spaces from a string in java without replaceAll():


  • Java Program to find the Duplicate Characters in a String

    We write a program to find duplicate characters in a string in java. For example, consider a string “nut cutter“, duplicate characters in it are : u: 2, t : 3.

    Program Approach:

    First, we created a string variable and take the user input for a string to compare with. And initialize a variable num to keep the number of counts. Then we convert the string variable to characters by creating a character array. Then with iteration(for loop), we compare the two characters and if the character of the compared index is matched, then we display that character with the increase of num with each iteration.

    The for loop will continue till the length of the entered string is finished.


    Java program of string to check duplicate characters.

    import java.util.Scanner;
    
    public class FindDuplicateCharacters 
    {
      public static void main(String[] args) 
      {
        String str;
        int num = 0;
        Scanner in = new Scanner(System.in);
      
        //Get input String
        System.out.println("Enter a string: ");
        str = in.nextLine();
         
        /*//if you want to define the string in a program
        //follow the below code and remove above
        String str = new String("simple2code.com");*/
          
          
        char[] chars = str.toCharArray();
          
        System.out.println("Duplicate characters are:");
          
        for (int i=0; i<str.length();i++) 
        {
          for(int j=i+1; j<str.length();j++) 
          {
             if (chars[i] == chars[j]) 
             {
                System.out.println(chars[j]);
                num++;
                break;
              }
          }
         }
       }
    }

    The output of duplicate characters in java

    Enter a string:
    simple2code.com
    Duplicate characters are:
    m
    e
    c
    o


  • Java Program to Check Whether Two Strings are Anagram Or Not

    This article on Anagram Program in java is to check for the two strings for Anagrams.
    Let start by understanding What is Anagram?

    What is Anagram?

    Two strings are said to be in an anagram if they contain the same set of characters but in a different order.

    For example: “Keep – peek”, “School Master – The Classroom”, “Debit Card – Bad Credit” etc.


    Java Program to check whether two Strings are Anagram Or Not

    import java.util.Arrays;
    
    public class Main
    {
      static void isAnagram(String str1, String str2)
      {
        String string1 = str1.replaceAll("\\s", "");
        String string2 = str2.replaceAll("\\s", "");
    
        boolean checkState = true;
    
        if (string1.length() != string2.length())
        {
          checkState = false;
        }
        else
        {
          char[] ArrayStr1 = string1.toLowerCase().toCharArray();
          char[] ArrayStr2 = string2.toLowerCase().toCharArray();
          Arrays.sort(ArrayStr1);
          Arrays.sort(ArrayStr2);
          checkState = Arrays.equals(ArrayStr1, ArrayStr2);
        }
    
        if (checkState)
        {
          System.out.println(string1 + " and " + string2 + " are anagrams");
        }
        else
        {
          System.out.println(string1 + " and " + string2 + " are not anagrams");
        }
      }
    
      public static void main(String[] args)
      {
        isAnagram("Keep", "Peek");
        isAnagram("The Classroom", "School Master");
        isAnagram("Debit Card", "Bad Credit");
        isAnagram("Mate", "Ate");
      }
    }

    The output of Java Program to check whether two Strings are Anagram Or Not

    Keep and Peek are anagrams
    TheClassroom and SchoolMaster are anagrams
    DebitCard and BadCredit are anagrams
    Mate and Ate are not anagrams


  • Java Program to Check the String for Palindrome

    Palindrome: A string is said to be in a Palindrome if it remains the same when its elements are reversed or are the same as forward.

    For example: 14141, 777, 272 are palindrome numbers as they remain the same even if reversed. If we take the example of ‘mam’ or ‘madam’, these are also palindrome words.


    Java program to check String is palindrome or not

     //check for the string Palindrome 
    
     import java.util.Scanner;
    
     public class StringPalindrome
     {
        public static void main(String args[])
        {
          String str1, str2= "";
          Scanner sc = new Scanner(System.in);
          
          System.out.print("Enter the String: ");
          str1 = sc.nextLine();
          
          for(int i = str1.length() - 1; i >= 0; i--)
          {
            str2 += str1.charAt(i);
          }
          
          //equalsIgnoreCase = This method returns true if the argument is not null and 
          //it represents an equivalent String ignoring case, else false
          if(str1.equalsIgnoreCase(str2))
          {
            System.out.println("The entered string is palindrome.");
          }
          else
          {
            System.out.println("The entered  string is not palindrome.");
          }
        }
     }

    Output:

    Enter the String: Madam
    The entered string is palindrome.


    Using StringBuilder’s reverse() function:

    Java program to check String is palindrome or not using the StringBuilder reverse() function. This function takes the string and reversed it or takes each of the elements from backward.

    import java.util.Scanner;
     
    public class Main {
     
     public static void main(String[] args) 
     {
       Scanner scanner = new Scanner(System.in);
       
       System.out.print("Enter the sstring to be check : ");
       String str = scanner.nextLine();
       
       StringBuilder strBdr = new StringBuilder(str);
       
       //reversing       
       strBdr.reverse();
       
       //Display      
       if(str.equals(strBdr.toString()))
       {
         System.out.println("Entered String is palindrome");
       } 
       else 
       {
         System.out.println("Entered String is not palindrome");
       }
     }
    }

    Output:

    Enter the sstring to be check : Madam
    Entered String is palindrome


  • Java Program to Reverse a String

    In this tutorial, we will write a program to reverse a string in Java. It means displaying the string from backward.

    Consider the string reverse, we write a java program in various ways to reverse it and it will be displayed as esrever. Some of the ways to do it are using:

    • for loop
    • recursion
    • StringBuffer.

    Write a java program to reverse a string:

    Using for loop

     //reverse a string 
    
     import java.util.Scanner;
    
     class ReversingString
     {
        public static void main(String args[])
        {
           String str, revString= "";
           Scanner in = new Scanner(System.in);
          
          //user input
           System.out.println("Enter a string: ");
           str= in.nextLine();
          
           int length = str.length();
          
           for (int i = length - 1 ; i >= 0 ; i--)
           {
            revString += str.charAt(i);
           }
            
           //display the reverse result
           System.out.println("Reverse of the entered string: " + revString);
        }
     }

    Output: when the code is is executed it shows the following result.

    Enter a string:
    I am learning java
    Reverse of the entered string: avaj gninrael ma I


    Using StringBuffer:

    In this method, we use reverse() method of StringBuffer class to reverse a string in java.

    //reverse a string Using StringBuffer
    
    import java.util.Scanner;
    
    class ReverseOfString
    {
      public static void main(String args[])
      {
        String str;
        Scanner in = new Scanner(System.in);
          
        //user input
        System.out.println("Enter the string: ");
        str= in.nextLine();
          
        //using StringBuffer
        StringBuffer sb = new StringBuffer(str);
        System.out.println("Reverse of entered string is:"+sb.reverse());
    
      }
    }

    Output:

    Enter the string:
    reverse
    Reverse of entered string is: esrever


    Using Recursion:

     //reverse a string using recursion 
    
     import java.util.Scanner;
    
     class Main
     {
      public static void main(String args[])
      {
        Main rvrs = new Main();
        
        String str, revString= "";
        Scanner in = new Scanner(System.in);
        //user input
        System.out.println("Enter a string: ");
        str= in.nextLine();
          
       String reverse = rvrs.reverseString(str);
       System.out.println("Reverse of entered string is: "+reverse);
    
      }
      
      public String reverseString(String str)
      {
      if ((null == str) || (str.length() <= 1))
         {
           return str;
         }
    
         return reverseString(str.substring(1)) + str.charAt(0);
      }
     }

    Output:

    Enter the string:
    reverse
    Reverse of entered string is: esrever


  • Java Program to Remove all the Vowels from a String

    This post shows, How to remove all vowels from a string in java? with the help of replaceAll() method.

    Remove vowels from a string in java:

    Explanation:
    Removing vowels in java is easy, we will take the user input with the help of a Scanner class. we will use replaceAll() which takes in two parameters, one is the string to be replaced and another one is the string to be replaced with.

    Also, the vowels are “aeiou” so we replace those vowel letters by an empty string (“”) for both uppercase and lowercase vowel letters. Then print the result string without vowels.


    Java Program to Remove all the Vowels from a String.

    import java.util.Scanner;
    
    public class RemoveVowel
    {
      public static void main(String[] args)
      {
        Scanner sc = new Scanner(System.in);
    
        //user input
        System.out.println("Enter the string:");
        String inputStr = sc.nextLine();
    
        String resultStr = inputStr.replaceAll("[AEIOUaeiou]", "");
    
        System.out.println("Result String without vowels:");
    
        System.out.println(resultStr);
    
        sc.close();
      }
    }

    The output of removing vowels from a string in java: