Print all permutations of String

Print all permutations of String

Example:

Input:  str="Java"
Output: All the permutations: 
Java, Jaav, Jvaa, Jvaa, Java, Jaav, aJva, aJav, avJa, avaJ, aavJ, aaJv, vaJa, vaaJ, vJaa, vJaa, vaJa, vaaJ, aavJ, aaJv, avaJ, avJa, aJva, aJav, 

Approach

Java

public class PermuteStringGen {

    public static void main(String[] args) {
        String str = "Java";
        int len = str.length();
        System.out.println("All the permutations: ");
        genPermutationS(str, 0, len);
    }

    // Method to generate all permutations
    public static void genPermutationS(String strint startint end) {
        // Prints the permutations
        if (start == end - 1)
            System.out.print(str + ", ");
        else {
            for (int i = start; i < end; i++) {
                // Swapping the string by fixing a character
                str = strSwap(str, start, i);
                // Recursively calling
                genPermutationS(str, start + 1, end);
                // Backtracking and swapping the characters again.
                str = strSwap(str, start, i);
            }
        }
    }
    // Swap
    public static String strSwap(String aint iint j) {
        char[] b = a.toCharArray();
        char ch;
        ch = b[i];
        b[i] = b[j];
        b[j] = ch;
        return String.valueOf(b);
    }

}


How to Generate Random Number in Java

How to Generate Random Number in Java

Approach: Using Math

Java



public class RandomNumber {
    public static void main(String[] args) {
        double num = Math.random();
        System.out.println(num);
    }
}

Approach: Generate a random number in between two number

Java



public class RandomNumber {
    public static void main(String[] args) {
        int start = 100, end = 200;
        int num = (int) (Math.random() * (end - start + 1) + start);
        System.out.println(num);
    }
}


Java Program to find all subsets of a string

Java Program to find all subsets of a string

All the possible subsets for a string will be n(n+1)/2.

Example:

Input:  str=JAVA
Output: All subsets for given string are: 
        J, JA, JAV, JAVA, A, AV, AVA, V, VA, A

Approach

Java


public class StringAllSubset {
    public static void main(String[] args) {

        String str = "JAVA";
        int len = str.length();
        int temp = 0;
        // Total possible subsets formula= n*(n+1)/2
        String arr[] = new String[len * (len + 1) / 2];

        // This loop maintains the starting character
        for (int i = 0; i < len; i++) {
            for (int j = i; j < len; j++) {
                arr[temp] = str.substring(i, j + 1);
                temp++;
            }
        }

        System.out.println("All subsets for given string are: ");
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}


Java Program to divide a string in 'N' equal parts.

Java Program to divide a string in 'N' equal parts.

To check whether the string can be divided into N equal parts, we need to divide the length of the string by n and assign the result to variable chars.

If the char comes out to be a floating-point value, we can't divide the string otherwise run for loop to traverse the string and divide the string at every chars interval.

Example:

Input:  str = "javajavajava";
Output: 3 equal parts of given string are 
        java java java

Approach

Java


public class DivideStringInNParts {
    public static void main(String[] args) {
        String str = "javajavajava";
        int len = str.length();
        int n = 3;
        int temp = 0, chars = len / n;
        // Stores the array of string
        String[] equalStr = new String[n];
        // Check whether a string can be divided into n equal parts
        if (len % n != 0) {
            System.out.println("Sorry length not devisable with given number");
        } else {
            for (int i = 0; i < len; i = i + chars) {
                String part = str.substring(i, i + chars);
                equalStr[temp] = part;
                temp++;
            }
            System.out.println(n + " equal parts of given string are ");
            for (int i = 0; i < equalStr.length; i++) {
                System.out.println(equalStr[i]);
            }
        }
    }
}


Java Program to count the total number of vowels and consonants in a string

As we know that, the characters a, e, i, o, u are known as vowels in the English alphabet. Any character other than that is known as the consonant.

Example:

Input:  str = "Java is A programming language!";
Output: Number of vowels: 11
Number of consonants: 15

Approach

Java


public class VowelConCount {
    public static void main(String[] args) {

        // Counter variable to store the count of vowels and consonant
        int vCount = 0, cCount = 0;

        // Declare a string
        String str = "Java is A programming language!";

        // Converting entire string to lower case to reduce the comparisons
        str = str.toLowerCase();

        for (int i = 0; i < str.length(); i++) {
            // Checks whether a character is a vowel
            if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o'
                    || str.charAt(i) == 'u') {
                vCount++;
            }
            // Checks whether a character is a consonant
            else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
                cCount++;
            }
        }
        System.out.println("Number of vowels: " + vCount);
        System.out.println("Number of consonants: " + cCount);
    }
}


Java Program to replace the spaces of a string with a specific character

Java Program to replace the spaces of a string with a specific character

Example:

Input:  str = "Java is the Programming Language";
Output: Java\is\the\Programming\Language

Approach

Java


public class ReplaceSpace {
    public static void main(String[] args) {
        String str = "Java is the Programming Language";
        char sChar = '\\';
        str = str.replace(' ', sChar);
        System.out.println(str);
    }
}


How to find if a string is present in a text file?

How to find if a string is present in a text file?

Example:

Input:  file - Java is the programming langualge.
Java is the programming langualge.
Output: Number of occurrences of Java is 2

Approach

Java


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FindingWordInFile {
    public static void main(String[] args) {
        String word = "Java";
        int count = findWord(word);

        if (count > 0) {
            System.out.println("File contains the specified word");
            System.out.println("Number of occurrences is: " + count);
        } else {
            System.out.println("File does not contain the specified word");
        }
    }

    private static int findWord(String word) {
        int count = 0;
        // Reading the contents of the file
        Scanner sc2 = null;
        try {
            sc2 = new Scanner(new FileInputStream("D:\\file.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        while (sc2.hasNextLine()) {
            String line = sc2.nextLine();
            System.out.println(line);
            if (line.indexOf(word) != -1) {
                count = count + 1;
            }
        }
        sc2.close();
        return count;
    }
}


Check if two string rotation of each other

Check if two string rotation of each other

Suppose we need to check whether string 2 is a rotation of string 1. To find this, we concatenate string 1 with string 1. Then, try to find the string 2 in concatenated string. If string 2 is present in concatenated string then, string 2 is rotation of string 1. String 2 deabc is found on the index 3 in concatenated string. So, deabc is rotation of abcde.

Example:

Input:  Str1=Java, str2=Java
Output: Rotation

Approach

Java


public class StringRotation {
    public static void main(String[] args) {
        String str1 = "Java", str2 = "Java";

        boolean flag = isRotation(str1, str2);
        if (flag) {
            System.out.println("Rotation");
        } else {
            System.out.println("Not a rotation");
        }
    }

    private static boolean isRotation(String str1String str2) {
        if (str1.length() != str2.length()) {
            return false;
        } else {
            // Concatenate both string
            str1 = str1.concat(str1);

            // Check whether str2 is present in str1
            if (str1.indexOf(str2) != -1)
                return true;
            else
                return false;
        }
    }
}

Approach 

Java


public class StringRotation {
    public static void main(String[] args) {
        String str1 = "Java", str2 = "Java";

        boolean flag = isRotation(str1, str2);
        if (flag) {
            System.out.println("Rotation");
        } else {
            System.out.println("Not a rotation");
        }
    }

    private static boolean isRotation(String s1String s2) {
        return s1.length() == s2.length() && (s1 + s1).indexOf(s2) != -1;
    }
}


Java Program to find maximum and minimum occurring character in a string

Java Program to find maximum and minimum occurring character in a string

Example:

Input:  Java is programming language
Output:Min freq : e, max freq : a

Approach

Java

import java.util.HashMap;

public class LargeAndSmallWord {
    public static void main(String[] args) {
        String str = "Java is programming language";
        HashMap<CharacterIntegerfreq = new HashMap<CharacterInteger>();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (!Character.isSpaceChar(ch)) {
                freq.put(ch, freq.getOrDefault(ch, 0) + 1);
            }
        }

        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        char minCh = '\0';
        char maxCh = '\0';

        for (Character ch : freq.keySet()) {
            if (min > freq.get(ch)) {
                minCh = ch;
                min = freq.get(ch);
            }
            if (max < freq.get(ch)) {
                maxCh = ch;
                max = freq.get(ch);
            }

        }
        System.out.println("Min freq : " + minCh + ", max freq : " + maxCh);

    }
}


Java Program to find the largest and smallest word in a string

Find the smallest and the largest word present in the string

Example:

Input:  Java is programming language
Output: smallest=is, largest=programming

Approach

Java


public class LargeAndSmallWord {
    public static void main(String[] args) {
        String str = "Java is programming language";
        String[] obj = str.split(" ");
        String small = "";
        String large = "";
        for (String string : obj) {
            if (small == "")
                small = string;
            // for largest word check
            if (string.length() > large.length()) {
                large = string;

            }
            // small word check
            if (small.length() > string.length())
                small = string;

        }
        System.out.println("smallest : " + small + ", largest : " + large);
    }
}

Approach

Java

public class LargeAndSmallWord {
    public static void main(String[] args) {
        String str = "Java is programming language";
        String small = "";
        String large = "";
        String strCh = "";
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (!Character.isSpaceChar(ch)) {
                strCh = strCh + ch;
                continue;
            }

            if (small == "")
                small = strCh;
            // for largest word check
            if (strCh.length() > large.length()) {
                large = strCh;

            }
            // small word check
            if (small.length() > strCh.length())
                small = strCh;

            // reset
            strCh = "";

        }
        System.out.println("smallest : " + small + ", largest : " + large);
    }
}