Sei sulla pagina 1di 79

String Data Structure

Strings are defined as an array of characters. The difference between a


character array and a string is the string is terminated with a special
character ‘\0’.
Declaring a string is as simple as declaring a one dimensional array.
Below is the basic syntax for declaring a string in C
programming language.
char str_name[size];

Strings in Java :

String class in Java | Set 1


String is a sequence of characters. In java, objects of String are
immutable which means a constant and cannot be changed once
created.
Creating a String
There are two ways to create string in Java:
 String literal
String s = “GeeksforGeeks”;

 Using new keyword
String s = new String (“GeeksforGeeks”);

Constructors
1. String(byte[] byte_arr) – Construct a new String by decoding
the byte array. It uses the platform’s default character set for
decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s_byte =new String(b_arr); //Geeks

2. String(byte[] byte_arr, Charset char_set) – Construct a new String


by decoding the byte array. It uses the char_set for decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
Charset cs = Charset.defaultCharset();
String s_byte_char = new String(b_arr, cs); //Geeks

3. String(byte[] byte_arr, String char_set_name) – Construct a new


String by decoding the byte array. It uses the char_set_name for
decoding.
It looks similar to the above constructs and they appear before
similar functions but it takes the String(which contains
char_set_name) as parameter while the above constructor
takes CharSet.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, "US-ASCII"); //Geeks
4. String(byte[] byte_arr, int start_index, int length) – Construct a
new string from the bytes array depending on
the start_index(Starting location) and length(number of characters
from starting location).
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, 1, 3); // eek

5. String(byte[] byte_arr, int start_index, int length, Charset


char_set) – Construct a new string from the bytes array depending
on the start_index(Starting location) and length(number of
characters from starting location).Uses char_set for decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
Charset cs = Charset.defaultCharset();
String s = new String(b_arr, 1, 3, cs); // eek

6. String(byte[] byte_arr, int start_index, int length, String


char_set_name) – Construct a new string from the bytes
array depending on the start_index(Starting
location) and length(number of characters from starting
location).Uses char_set_name for decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, 1, 4, "US-ASCII"); // eeks

7. String(char[] char_arr) – Allocates a new String from the


given Character array
Example:
char char_arr[] = {'G', 'e', 'e', 'k', 's'};
String s = new String(char_arr); //Geeks

8. String(char[] char_array, int start_index, int count) – Allocates a


String from a given character array but choose count characters
from the start_index.
Example:
char char_arr[] = {'G', 'e', 'e', 'k', 's'};
String s = new String(char_arr , 1, 3); //eek

9. String(int[] uni_code_points, int offset, int count) – Allocates a


String from a uni_code_array but choose count characters from
the start_index.
Example:
int[] uni_code = {71, 101, 101, 107, 115};
String s = new String(uni_code, 1, 3); //eek

10. String(StringBuffer s_buffer) – Allocates a new string from the


string in s_buffer
Example:
StringBuffer s_buffer = new StringBuffer("Geeks");
String s = new String(s_buffer); //Geeks

11. String(StringBuilder s_builder) – Allocates a new string from the


string in s_builder
Example:
StringBuilder s_builder = new StringBuilder("Geeks");
String s = new String(s_builder); //Geeks

String Methods
1. int length(): Returns the number of characters in the String.
"GeeksforGeeks".length();  // returns 13
2.
3. Char charAt(int i): Returns the character at ith index.
"GeeksforGeeks".charAt(3); // returns  ‘k’
4.
5. String substring (int i): Return the substring from the ith  index
character to end.
"GeeksforGeeks".substring(3); // returns “ksforGeeks”
6. String substring (int i, int j): Returns the substring from i to j-1
index.
"GeeksforGeeks".substring(2, 5); // returns “eks”
7. String concat( String str): Concatenates specified string to the end
of this string.
String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “GeeksforGeeks”
8. int indexOf (String s): Returns the index within the string of the
first occurrence of the specified string.
String s = ”Learn Share Learn”;
int output = s.indexOf(“Share”); // returns 6
9. int indexOf (String s, int i): Returns the index within the string of
the first occurrence of the specified string, starting at the specified
index.
String s = ”Learn Share Learn”;
int output = s.indexOf("ea",3);// returns 13
10. Int lastIndexOf( String s): Returns the index within the string of the
last occurrence of the specified string.
String s = ”Learn Share Learn”;
int output = s.lastIndexOf("a"); // returns 14
11. boolean equals( Object otherObj): Compares this string to the
specified object.
Boolean out = “Geeks”.equals(“Geeks”); // returns true
Boolean out = “Geeks”.equals(“geeks”); // returns false
12. boolean  equalsIgnoreCase (String anotherString): Compares
string to another string, ignoring case considerations.
Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true
Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true
13.  int compareTo( String anotherString): Compares two string
lexicographically.
int out = s1.compareTo(s2);  // where s1 ans s2 are
// strings to be compared

This returns difference s1-s2. If :


out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
14. int compareToIgnoreCase( String anotherString): Compares two
string lexicographically, ignoring case considerations.
int out = s1.compareToIgnoreCase(s2); 
// where s1 ans s2 are
// strings to be compared

This returns difference s1-s2. If :


out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.

Note- In this case, it will not consider case of a letter (it will ignore
whether it is uppercase or lowercase).
15. String toLowerCase(): Converts all the characters in the String to
lower case.
String word1 = “HeLLo”;
String word3 = word1.toLowerCase(); // returns “hello"
16. String toUpperCase(): Converts all the characters in the String to
upper case.
String word1 = “HeLLo”;
String word2 = word1.toUpperCase(); // returns “HELLO”
17. String trim(): Returns the copy of the String, by removing
whitespaces at both ends. It does not affect whitespaces in the
middle.
String word1 = “ Learn Share Learn “;
String word2 = word1.trim(); // returns “Learn Share Learn”
18.  String replace (char oldChar, char newChar): Returns new string
by replacing all occurrences of oldChar with newChar.
String s1 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns “geeksgorgeeks”
Note:- s1 is still feeksforfeeks and s2 is geeksgorgeeks
Program to illustrate all string  methods:

String in Switch Case in Java


Switch Statement in Java
Beginning with JDK 7, we can use a string literal/constant to control a
switch statement, which is not possible in C/C++. Using a string-based
switch is an improvement over using the equivalent sequence of if/else
statements.
Important Points:
 Expensive operation: Switching on strings can be more expensive
in term of execution than switching on primitive data types.
Therefore, it is best to switch on strings only in cases in which the
controlling data is already in string form.
 String should not be NULL: Ensure that the expression in any
switch statement is not null while working with strings to prevent a
NullPointerException from being thrown at run-time.
 Case Sensitive Comparison: The switch statement compares the
String object in its expression with the expressions associated with
each case label as if it were using the String.equals method;
consequently, the comparison of String objects in switch
statements is case sensitive.
 Better than if-else: The Java compiler generates generally more
efficient bytecode from switch statements that use String objects
than from chained if-then-else statements.

// Java program to demonstrate use of a


// string to control a switch statement.
public class Test 
{
    public static void main(String[] args)
    {
        String str = "two";
        switch(str)
        {
            case "one":
                System.out.println("one");
                break;
            case "two":
                System.out.println("two");
                break;
            case "three":
                System.out.println("three");
                break;
            default:
                System.out.println("no match");
        }
    }
}

Output:
two
Java program to swap first and last
characters of words in a sentence
Write a Java Program to Swap first and last character of words in a
Sentence as mentioned in the example?
Examples:
Input : geeks for geeks
Output :seekg rof seekg
Approach:As mentioned in the example we have to replace first and last
character of word and keep rest of the alphabets as it is.

 First we will create an Char array of given String by using


toCharArray() method.
 Now we iterate the char array by using for loop.
 In for loop, we declare a variable whose value is dependent on i.
 Whenever we found an alphabet we increase the value of i and
whenever we reach at space, we are going to perform swapping
between first and last character of the word which is previous of
space.
class SwapFirstLastCharacters {
    static String count(String str)
    {
        // Create an equivalent char array
        // of given string
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
  
            // k stores index of first character
            // and i is going to store index of last 
            // character. 
            int k = i;
            while (i < ch.length && ch[i] != ' ') 
                i++;
              
            // Swapping
            char temp = ch[k];
            ch[k] = ch[i - 1];
            ch[i - 1] = temp;
  
            // We assume that there is only one space
            // between two words.
        }
        return new String(ch);
    }
    public static void main(String[] args)
    {
        String str = "geeks for geeks";
        System.out.println(count(str));
    }
}
Output:
seekg rof seekg

Java program to expand a String if


range is given?
Suppose we have given a String in which some ranges as specified and
we have to place the numbers which is between the given range in the
specified place as given in the example:
Examples:
Input : string x = "1-5, 8, 11-14, 18, 20, 26-29"
Output : string y = "1, 2, 3, 4, 5, 8, 11, 12,
13, 14, 18, 20, 26, 27, 28, 29"
Approach: To solve the above problem, we can follow the below
approach:

 First we have to split the String into String[] array. We have to split
the String where we found – symbol.

 Now we have String[] array with the elements. Now we just go to


the first index last element i.e. 1 and preceding index first element
of the String[] array i.e. 5 .
 After that by the help of for loop we can add the numbers which is
between 1 and 5 and store it in the String variable.
 The above process continue til the length of String[] array.
NOTE: By the help of Collections and various utility methods we can
solve the problem easily but Collections concept is not good option
performance wise. If we go through Collections, performance is reduced
and time complexity is also increased.There in the below program we
explicitly define our own split method and logic.
// Java code to demonstrate expansion
// of string
  
public class StringExpand {
  
    static String[] split(String st)
    {
        // Count how many words in our string
        // Irrespective of spaces
        int wc = countWords(st);
        String w[] = new String[wc];
        char[] c = st.toCharArray();
        int k = 0;
        for (int i = 0; i < c.length; i++) {
            String s = "";
  
            // Whenever we found an non-space character
            while (i < c.length && c[i] != ' ') {
                // Concat with the String s
                // Increment the value of i
                s = s + c[i];
                i++;
            }
  
            // If the String is not empty
            if (s.length() != 0) {
  
                // Add the String to the String[] 
                // array
                w[k] = s;
                k++;
            }
        }
  
        // Returning the String[] array
        return w;
    }
  
    static int countWords(String str)
    {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
  
            // The below condition to check
            // whether the first character is 
            // space or not
            if (i == 0 && str.charAt(i) != ' ' || 
                str.charAt(i) != ' ' && 
                str.charAt(i - 1) == ' ') {
                count++;
            }
        }
        return count;
    }
  
    public static void expand(String s)
    {
        String p = s;
        String[] arr = p.split("\\-");
        String k = "";
        for (int i = 0; i < arr.length; i++) {
            if (i != arr.length - 1) {
                String[] arr1 = arr[i].split(", ");
                String[] arr2 = arr[i + 1].split(", ");
                int a = Integer.parseInt(arr1[arr1.length -
1]);
                int b = Integer.parseInt(arr2[0]);
                for (int j = a + 1; j < b; j++) {
                    arr[i] = arr[i] + ", " + j;
                }
            }
            if (k != "")
                k = k + ", " + arr[i];
            else
                k = k + arr[i];
        }
  
        System.out.println(k);
    }
  
    // Driver code 
    public static void main(String[] args)
    {
        String s = "1-5, 8, 11-14, 18, 20, 26-29";
        expand(s);
    }
}
Output:
1, 2, 3, 4, 5, 8, 11, 12, 13, 14, 18, 20, 26, 27, 28, 29
Check if a given string is a valid
number (Integer or Floating Point) in
Java | SET 2 (Regular Expression
approach)
In Set 1, we have discussed general approach to check whether a string
is a valid number or not. In this post, we will discuss regular
expression approach to check for a number.
Examples:
Input : str = "11.5"
Output : true

Input : str = "abc"


Output : false

Input : str = "2e10"


Output : true

Input : 10e5.4
Output : false

Check if a given string is a valid Integer


For integer number : Below is the regular definition for an integer
number.
sign -> + | - | epsilon
digit -> 0 | 1 | .... | 9
num -> sign digit digit*
Hence one of the regular expression for an integer number is
[+-]?[0-9][0-9]*
// Java program to check whether given string
// is a valid integer number using regex
  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
class GFG 
{
    public static void main (String[] args)
    {
        String input1 = "abc";
        String input2 = "1234";
          
        // regular expression for an integer number
        String regex = "[+-]?[0-9][0-9]*";
          
        // compiling regex
        Pattern p = Pattern.compile(regex);
          
        // Creates a matcher that will match input1 against
regex
        Matcher m = p.matcher(input1);
          
        // If match found and equal to input1
        if(m.find() && m.group().equals(input1))
            System.out.println(input1 + " is a valid integer
number");
        else
            System.out.println(input1 + " is not a valid
integer number");
          
        // Creates a matcher that will match input2 against
regex
        m = p.matcher(input2);
          
        // If match found and equal to input2
        if(m.find() && m.group().equals(input2))
                System.out.println(input2 + " is a valid
integer number");    
        else
            System.out.println(input2 + " is not a valid
integer number");
    }
}

Output:
abc is not a valid integer number
1234 is a valid integer number
Below are other short-hands regular expression for an integer number
[+-]?[0-9]+
[+-]?\d\d*
[+-]?\d+
Check if a given string is a valid floating point number
For floating point number : Below is the regular definition for a floating
point number.
sign -> + | - | epsilon
digit -> 0 | 1 | .... | 9
digits -> digit digit*
optional_fraction -> . digits | epsilon
optional_exponent -> ((E | e) (+ | - | epsilon) digits) | epsilon
num -> sign digits optional_fraction optional_exponent
Hence one of the regular expression for a floating number is
[+-]?[0-9]+(\.[0-9]+)?([Ee][+-]?[0-9]+)?

//Java program to check whether given string


// is a valid floating point number using regex
  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
class GFG 
{
    public static void main (String[] args)
    {
        String input1 = "10e5.4";
        String input2 = "2e10";
          
        // regular expression for a floating point number
        String regex = "[+-]?[0-9]+(\\.[0-9]+)?([Ee][+-]?[0-
9]+)?";
          
        // compiling regex
        Pattern p = Pattern.compile(regex);
          
        // Creates a matcher that will match input1 against
regex
        Matcher m = p.matcher(input1);
          
        // If match found and equal to input1
        if(m.find() && m.group().equals(input1))
            System.out.println(input1 + " is a valid float
number");
        else
            System.out.println(input1 + " is not a valid float
number");
          
        // Creates a matcher that will match input2 against
regex
        m = p.matcher(input2);
          
        // If match found and equal to input2
        if(m.find() && m.group().equals(input2))
                System.out.println(input2 + " is a valid float
number");    
        else
            System.out.println(input2 + " is not a valid float
number");
    }
}

Output:
10e5.4 is not a valid float number
2e10 is a valid float number
Below is other short-hand regular expression for a float number
[+-]?\d+(\.\d+)?([Ee][+-]?\d+)?

Reverse words in a given String in Java


Let’s see an approach to reverse words of a given String in Java without
using any of the String library function
Examples:
Input : "Welcome to geeksforgeeks"
Output : "geeksforgeeks to Welcome"

Input : "I love Java Programming"


Output :"Programming Java love I"

// Java Program to reverse a String


// without using inbuilt String function
import java.util.regex.Pattern;
public class Exp {
  
    // Method to reverse words of a String
    static String reverseWords(String str)
    {
  
        // Specifying the pattern to be searched
        Pattern pattern = Pattern.compile("\\s");
  
        // splitting String str with a pattern
        // (i.e )splitting the string whenever their
        //  is whitespace and store in temp array.
        String[] temp = pattern.split(str);
        String result = "";
  
        // Iterate over the temp array and store
        // the string in reverse order.
        for (int i = 0; i < temp.length; i++) {
            if (i == temp.length - 1)
                result = temp[i] + result;
            else
                result = " " + temp[i] + result;
        }
        return result;
    }
  
    // Driver methods to test above method
    public static void main(String[] args)
    {
        String s1 = "Welcome to geeksforgeeks";
        System.out.println(reverseWords(s1));
  
        String s2 = "I love Java Programming";
        System.out.println(reverseWords(s2));
    }
}

Output:
geeksforgeeks to Welcome
Programming Java love I

Reverse a string in Java


This article discusses 5 different ways to reverse a string in Java with
examples.
Examples:

Prerequisite : String vs StringBuilder vs StringBuffer in Java


Following are some interesting facts about String and StringBuffer
classes :
1. Objects of String are immutable.
2. String class in Java does not have reverse() method, however
StringBuilder class has built in reverse() method.
3. StringBuilder class do not have toCharArray() method, while String
class does have toCharArray() method.
1.Converting String into Bytes: getBytes() method is used to convert the
input string into bytes[].
Method:
1. Create a temporary byte[] of length equal
to the length of the input string.
2. Store the bytes (which we get by using
getBytes() method) in reverse order into
the temporary byte[] .
3. Create a new String abject using byte[] to
store result.

// Java program to ReverseString using ByteArray.


import java.lang.*;
import java.io.*;
import java.util.*;
  
// Class of ReverseString
class ReverseString
{
    public static void main(String[] args)
    {
        String input = "GeeksforGeeks";
  
        // getBytes() method to convert string 
        // into bytes[].
        byte [] strAsByteArray = input.getBytes();
  
        byte [] result = 
                   new byte [strAsByteArray.length];
  
        // Store result in reverse order into the
        // result byte[]
        for (int i = 0; i<strAsByteArray.length; i++)
            result[i] = 
             strAsByteArray[strAsByteArray.length-i-1];
  
        System.out.println(new String(result));
    }
}
Output:
skeeGrofskeeG

2. Usingbuilt in reverse() method of the StringBuilder class: String class


does not have reverse() method, we need to convert the input string to
StringBuilder, which is achieved by using the append method of
StringBuilder. After that, print out the characters of the reversed string
by scanning from the first till the last index.

// Java program to ReverseString using StringBuilder


import java.lang.*;
import java.io.*;
import java.util.*;
  
// Class of ReverseString
class ReverseString
{
    public static void main(String[] args)
    {
        String input = "Geeks for Geeks";
  
        StringBuilder input1 = new StringBuilder();
  
        // append a string into StringBuilder input1
        input1.append(input);
  
        // reverse StringBuilder input1
        input1 = input1.reverse();
  
        // print reversed String
        System.out.println(input1);
    }
}
Output:
skeeG rof skeeG

3. Converting String to character array: The user input the string to be


reversed.
Method:
1. First, convert String to character array
by using the built in Java String class
method toCharArray().
2. Then, scan the string from end to start,
and print the character one by one.

// Java program to Reverse a String  by


// converting string to characters  one
// by one
import java.lang.*;
import java.io.*;
import java.util.*;
  
// Class of ReverseString
class ReverseString
{
    public static void main(String[] args)
    {
        String input = "GeeksForGeeks";
  
        // convert String to character array
        // by using toCharArray
        char[] try1 = input.toCharArray();
  
        for (int i = try1.length-1; i>=0; i--)
            System.out.print(try1[i]);
    }
}
Output:
skeeGrofskeeG
4. Convert the input string into character array by using the
toCharArray(): Convert the input string into character array by
using the toCharArray() – built in method of the String Class. Then,
scan the character array from both sides i.e from the start index
(left) as well as from last index(right) simultaneously.
1. Set the left index equal to 0 and right
index equal to the length of the string -1.
2. Swap the characters of the start index
scanning with the last index scanning
one by one. After that, increase the left
index by 1 (left++) and decrease the right
by 1 i.e., (right--) to move on to the next
characters in the character array .
3. Continue till left is less than or equal to
the right.
// Java program to Reverse a String using swapping
// of variables
import java.lang.*;
import java.io.*;
import java.util.*;
  
// Class of ReverseString
class ReverseString
{
    public static void main(String[] args)
    {
        String input = "Geeks For Geeks";
        char[] temparray = input.toCharArray();
        int left, right=0;
        right = temparray.length-1;
  
        for (left=0; left < right ; left++ ,right--)
        {
            // Swap values of left and right
            char temp = temparray[left];
            temparray[left] = temparray[right];
            temparray[right]=temp;
        }
  
        for (char c : temparray)
            System.out.print(c);
        System.out.println();
    }
}
Output:
skeeG roF skeeG
5. Using ArrayList object: Convert the input string into the character
array by using toCharArray() built in method. Then, add the characters of
the array into the ArrayList object. Java also has built in reverse()
method for the Collections class. Since Collections class reverse()
method takes a list object , to reverse the list , we will pass the ArrayList
object which is a type of list of characters.
1. We copy String contents to an object
of ArrayList.
1. We create a ListIterator object by using
the listIterator() method on the ArrayList
object.
2. ListIterator object is used to iterate over
the list.
3. ListIterator object helps us to iterate
over the reversed list and print it one
by one to the output screen.
// Java program to Reverse a String using ListIterator
import java.lang.*;
import java.io.*;
import java.util.*;
  
// Class of ReverseString
class ReverseString
{
    public static void main(String[] args)
    {
        String input = "Geeks For Geeks";
        char[] hello = input.toCharArray();
        List<Character> trial1 = new ArrayList<>();
  
        for (char c: hello)
            trial1.add(c);
  
        Collections.reverse(trial1);
        ListIterator li = trial1.listIterator();
        while (li.hasNext())
            System.out.print(li.next());
    }
}
Output:
skeeG roF skeeG

Compare two strings lexicographically


in Java
In this article, we will discuss how we can compare two strings
lexicographically in Java.
One solution is to use Java compareTo() method. The method
compareTo() is used for comparing two strings lexicographically in Java.
Each character of both the strings is converted into a Unicode value for
comparison.
int compareTo(String str) :
It returns the following values:

1. if (string1 > string2) it returns a positive value.


2. if both the strings are equal lexicographically
i.e.(string1 == string2) it returns 0.
3. if (string1 < string2) it returns a negative value.
// Java program to show how to compare Strings
// using library function
public class Test
{
    public static void main(String[] args)
    {
        String s1 = "Ram";
        String s2 = "Ram";
        String s3 = "Shyam";
        String s4 = "ABC";
  
        System.out.println(" Comparing strings with
compareto:");
        System.out.println(s1.compareTo(s2));
        System.out.println(s1.compareTo(s3));
        System.out.println(s1.compareTo(s4));
    }
}
Output :
Comparing strings with compareto:
0
-1
17
How to compare two strings without using library function?
1. Input two strings string 1 and string 2.
2. for (int i = 0; i < str1.length() &&
i < str2.length(); i ++)
(Loop through each character of both
strings comparing them until one
of the string terminates):
a. If unicode value of both the characters
is same then continue;
b. If unicode value of character of
string 1 and unicode value of string 2
is different then return (str1[i]-str2[i])
3. if length of string 1 is less than string2
return str2[str1.length()]
else
return str1[str2.length()]
Below is the implementation of above algorithm.
// Java program to Compare two strings
// lexicographically
class Compare {
  
    // This method compares two strings
    // lexicographically without using
    // library functions
    public static int stringCompare(String str1,
                                    String str2)
    {
        for (int i = 0; i < str1.length() && 
                    i < str2.length(); i++) {
            if ((int)str1.charAt(i) == 
                (int)str2.charAt(i)) {
                continue;
            } 
            else {
                return (int)str1.charAt(i) - 
                    (int)str2.charAt(i);
            }
        }
  
        // Edge case for strings like
        // String 1="Geeky" and String 2="Geekyguy"
        if (str1.length() < str2.length()) {
            return (str1.length()-str2.length());
        } 
        else if (str1.length() > str2.length()) {
            return (str1.length()-str2.length());
        }
          
        // If none of the above conditions is true,
        // it implies both the strings are equal
        else {
            return 0;
        }
    }
  
    // Driver function to test the above program
    public static void main(String args[])
    {
        String string1 = new String("Geeks");
        String string2 = new String("Practice");
        String string3 = new String("Geeks");
        String string4 = new String("Geeksforgeeks");
      
        System.out.println(stringCompare(string1, 
                                        string2));
        System.out.println(stringCompare(string1, 
                                        string3));
        System.out.println(stringCompare(string2,
                                        string1));
  
        // To show for edge case
        // In these cases, the output is the difference of 
        // length of the string
        System.out.println(stringCompare(string1,
                                        string4));
        System.out.println(stringCompare(string4,
                                        string1));
    }
}
Output :
-9
0
9
-8
8

Searching characters and substring in a


String in Java
Searching a character in the String
 indexOf(char c) : It searches the index of specified character
within a given string. It starts searching from beginning to the end
of the string (from left to right) and returns the corresponding index
if found otherwise returns -1.
Note: If given string contains multiple occurrence of specified
character then it returns index of only first occurrence of specified
character.
Syntax:
int indexOf(char c)
// Accepts character as argument, Returns index of
// the first occurrence of specified character

 lastIndexOf(char c): It starts searching backward from end of the
string and returns the index of specified character whenever it is
encountered.
Syntax:
public int lastIndexOf(char c)
// Accepts character as argument, Returns an
// index of the last occurrence specified
// character

 IndexOf(char c, int indexFrom): It starts searching forward from
the specified index in the string and returns the corresponding
index when the specified character is encountered otherwise
returns -1. Note: The returned index must be greater than or equal
to the specified index.
Syntax:
public int IndexOf(char c, int indexFrom)
char: character to be searched.
indexfrom : an integer from where searching
// Returns an index of specified character that
// appeared at or after the specified index in
// forward direction

 lastIndexOf(char c, int fromIndex): It starts searching backward
from the specified index in the string. And returns the
corresponding index when the specified character is encountered
otherwise returns -1.
Note: The returned index must be less than or equal to the
specified index.
Syntax:
public int lastIndexOf(char c, int fromIndex)

 charAt(int indexNumber): Returns the character existing at the
specified index, indexNumber in the given string. If the specified
index number does not exist in the string, the method throws an
unchecked exception, StringIndexOutOfBoundsException.
Syntax:
char charAt(int indexNumber)

// Java program to illustrate to find a character


// in the string.
import java.io.*;
  
class GFG
{
  public static void main (String[] args)
  {
    // This is a string in which a character
    // to be searched.
    String str = "GeeksforGeeks is a computer science portal";
  
    // Returns index of first occurrence of character.
    int firstIndex = str.indexOf('s');
    System.out.println("First occurrence of char 's'" +
                       " is found at : " + firstIndex);
  
    // Returns index of last occurrence specified character.
    int lastIndex = str.lastIndexOf('s');
    System.out.println("Last occurrence of char 's' is" +
                       " found at : " + lastIndex);
  
    // Index of the first occurrence of specified char
    // after the specified index if found.
    int first_in = str.indexOf('s', 10);
    System.out.println("First occurrence of char 's'" +
                       " after index 10 : " + first_in);
  
    int last_in = str.lastIndexOf('s', 20);
    System.out.println("Last occurrence of char 's'" +
                     " after index 20 is : " + last_in);
  
    // gives ASCII value of character at location 20
    int char_at = str.charAt(20);
    System.out.println("Character at location 20: " +
                                             char_at);
  
    // throws StringIndexOutOfBoundsException
    // char_at = str.charAt(50);
  }
}

Output:

First occurrence of char 's' is found at : 4


Last occurrence of char 's' is found at : 28
First occurrence of char 's' after index 10 : 12
Last occurrence of char 's' after index 20 is : 15
Character at location 20: 111

Searching Substring in the String


The methods used for searching a character in the string which are
mentioned above can also be used for searching the substring in the
string.

// Java program to illustrate to find a substring


// in the string.
import java.io.*;
  
class GFG
{
  public static void main (String[] args)
  {
    // This is a string in which a substring
    // is to be searched.
    String str = "GeeksforGeeks is a computer science portal";
  
    // Returns index of first occurrence of substring
    int firstIndex = str.indexOf("Geeks");
    System.out.println("First occurrence of char Geeks"+
               " is found at : " + firstIndex);
  
    // Returns index of last occurrence
    int lastIndex = str.lastIndexOf("Geeks");
    System.out.println("Last occurrence of char Geeks is"+
               " found at : " + lastIndex);
  
    // Index of the first occurrence
    // after the specified index if found.
    int first_in = str.indexOf("Geeks", 10);
    System.out.println("First occurrence of char Geeks"+
               " after index 10 : " + first_in);
  
    int last_in = str.lastIndexOf("Geeks", 20);
    System.out.println("Last occurrence of char Geeks " +
               "after index 20 is : " + last_in);
  }
}

Output:

First occurrence of char Geeks is found at : 0


Last occurrence of char Geeks is found at : 8
First occurrence of char Geeks after index 10 : -1
Last occurrence of char Geeks after index 20 is : 8

contains(CharSequence seq): It returns true if the String contains the


specified sequence of char values otherwise returns false. Its
parameters specify sequence of character to be searched and throws
NullPointer exception if seq is null.
public boolean contains(CharSequence seq)

Note: CharSequence is an interface that is implemented by String class,


Therefore we use string as an argument in contains() method.

Matching String Start and End


 boolean startsWith(String str): Returns true if the string str exist
at the starting of the given string, else false.
 boolean startsWith(String str, int indexNum): Returns true if the
string str exist at the starting of the index indexNum in the given
string, else false.
 boolean endsWith(String str): Returns true if the string str exist at
the ending of the given string, else false.
// Java program to illustrate to match
// of start and end of a substring
import java.io.*;
  
class GFG
{
  public static void main (String[] args)
  {
    // This is a string in which substring
    // is to be searched.
    String str = "GeeksforGeeks is a computer science portal";
  
    System.out.println(str.startsWith("Geek"));
    System.out.println(str.startsWith("is", 14));
    System.out.println(str.endsWith("port"));
  }
}
Output:
true
true
false
// Java code to illustrate different constructors and methods 
// String class.
  
import java.io.*;
import java.util.*;
class Test
{
    public static void main (String[] args)
    {
        String s= "GeeksforGeeks";
        // or String s= new String ("GeeksforGeeks");
  
        // Returns the number of characters in the String.
        System.out.println("String length = " + s.length());
  
        // Returns the character at ith index.
        System.out.println("Character at 3rd position = "
                           + s.charAt(3));
  
        // Return the substring from the ith  index character
        // to end of string
        System.out.println("Substring " + s.substring(3));
  
        // Returns the substring from i to j-1 index.
        System.out.println("Substring  = " +
s.substring(2,5));
  
        // Concatenates string2 to the end of string1.
        String s1 = "Geeks";
        String s2 = "forGeeks";
        System.out.println("Concatenated string  = " +
                            s1.concat(s2));
  
        // Returns the index within the string
        // of the first occurrence of the specified string.
        String s4 = "Learn Share Learn";
        System.out.println("Index of Share " + 
                           s4.indexOf("Share"));
  
        // Returns the index within the string of the
        // first occurrence of the specified string,
        // starting at the specified index.
        System.out.println("Index of a  = " + 
                           s4.indexOf('a',3));
  
        // Checking equality of Strings
        Boolean out = "Geeks".equals("geeks");
        System.out.println("Checking Equality  " + out);
        out = "Geeks".equals("Geeks");
        System.out.println("Checking Equality  " + out);
  
        out = "Geeks".equalsIgnoreCase("gEeks ");
        System.out.println("Checking Equality " + out);
  
        int out1 = s1.compareTo(s2);
        System.out.println("If s1 = s2 " + out);
  
        // Converting cases
        String word1 = "GeeKyMe";
        System.out.println("Changing to lower Case " +
                            word1.toLowerCase());
  
        // Converting cases
        String word2 = "GeekyME";
        System.out.println("Changing to UPPER Case " + 
                            word1.toUpperCase());
  
        // Trimming the word
        String word4 = " Learn Share Learn ";
        System.out.println("Trim the word " + word4.trim());
  
        // Replacing characters
        String str1 = "feeksforfeeks";
        System.out.println("Original String " + str1);
        String str2 = "feeksforfeeks".replace('f' ,'g') ;
        System.out.println("Replaced f with g -> " + str2);
    } 
}
Output :
String length = 13
Character at 3rd position = k
Substring ksforGeeks
Substring = eks
Concatenated string = GeeksforGeeks
Index of Share 6
Index of a = 8
Checking Equality false
Checking Equality true
Checking Equality false
If s1 = s2 false
Changing to lower Case geekyme
Changing to UPPER Case GEEKYME
Trim the word Learn Share Learn
Original String feeksforfeeks
Replaced f with g -> geeksgorgeeks
Basics :
Function to copy string (Iterative and Recursive)
Examples:
Input : s1 = "hello"
s2 = "geeksforgeeks"
Output : s2 = "hello"

Input : s1 = "geeksforgeeks"
s2 = ""
Output : s2 = "geeksforgeeks"
Iterative :
Copy every character from s1 to s2 starting from index = 0 and in each
call increase the index by 1 until s1 doesn’t reach to end;

// Iterative Java Program to copy one String 


// to another.
class GFG
{
      
// Function to copy one string to other
// assuming that other string has enough
// space.
static void myCopy(char s1[], char s2[])
{
    int i = 0;
    for (i = 0; i < s1.length; i++)
         s2[i] = s1[i];
}
  
// Driver code
public static void main(String[] args) 
{
    char s1[] = "GEEKSFORGEEKS".toCharArray();
    char s2[] = new char[s1.length];
    myCopy(s1, s2);
    System.out.println(String.valueOf(s2));
}
}
Output:
GEEKSFORGEEKS
Recursive :
Copy every character from s1 to s2 starting from index = 0 and in each
call increase the index by 1 until s1 doesn’t reach to end;

// Java Program to copy one String to 


// another using Recursion 
class GFG 
{
      
    // Function to copy one string in to other 
    // using recursion 
    static void myCopy(char s1[], 
                       char s2[], int index) 
    {
        // copying each character from s1 to s2 
        s2[index] = s1[index];
  
        // if string reach to end then stop 
        if (index == s1.length - 1)
        {
            return;
        }
  
        // increase character index by one 
        myCopy(s1, s2, index + 1);
    }
  
    // Driver Code 
    public static void main(String[] args) 
    {
        char s1[] = "GEEKSFORGEEKS".toCharArray();
        char s2[] = new char[s1.length];
        int index = 0;
        myCopy(s1, s2, index);
        System.out.println(String.valueOf(s2));
    }
}
Output:
GEEKSFORGEEKS

Pangram Checking
Given a string check if it is Pangram or not. A pangram is a sentence
containing every letter in the English Alphabet.
Examples : The quick brown fox jumps over the lazy dog ” is a Pangram
[Contains all the characters from ‘a’ to ‘z’]
“The quick brown fox jumps over the dog” is not a Pangram [Doesn’t
contains all the characters from ‘a’ to ‘z’, as ‘l’, ‘z’, ‘y’ are missing]
We create a mark[] array of Boolean type. We iterate through all the
characters of our string and whenever we see a character we mark it.
Lowercase and Uppercase are considered the same. So ‘A’ and ‘a’ are
marked in index 0 and similarly ‘Z’ and ‘z’ are marked in index 25.

After iterating through all the characters we check whether all the
characters are marked or not. If not then return false as this is not a
pangram else return true.
// Java Program to illustrate Pangram
class GFG 
{
  
    // Returns true if the string
    // is pangram else false
    public static boolean checkPangram (String str)
    {
        // Create a hash table to mark the 
        // characters present in the string
        // By default all the elements of 
        // mark would be false.
        boolean[] mark = new boolean[26];
  
        // For indexing in mark[]
        int index = 0;
  
        // Traverse all characters
        for (int i = 0; i < str.length(); i++)
        {
            // If uppercase character, subtract 'A'
            // to find index.
            if ('A' <= str.charAt(i) && 
                    str.charAt(i) <= 'Z')
                          
                index = str.charAt(i) - 'A';
  
                // If lowercase character, subtract 'a'
                // to find index.
            else if('a' <= str.charAt(i) && 
                        str.charAt(i) <= 'z')
                              
                index = str.charAt(i) - 'a';
  
            // Mark current character
            mark[index] = true;
        }
  
        // Return false if any character is unmarked
        for (int i = 0; i <= 25; i++)
            if (mark[i] == false)
                return (false);
  
        // If all characters were present
        return (true);
    }
  
    // Driver Code
    public static void main(String[] args) 
    {
        String str = "The quick brown fox jumps over the lazy
dog";
  
        if (checkPangram(str) == true)
            System.out.print(str + " is a pangram.");
        else
            System.out.print(str+ " is not a pangram.");
  
    }
}
Output :
"The quick brown fox jumps over the lazy dog"
is a pangram
Time Complexity: O(n), where n is the length of our string
Auxiliary Space – O(1)

Removing punctuations from a given


string
Given a string, remove the punctuation from the string if the given
character is a punctuation character as classified by the current C locale.
The default C locale classifies these characters as punctuation:
!"#$%&'()*+,-./:;?@[\]^_`{|}~
Examples:
Input : %welcome' to @geeksforgeek<sOutput : welcome to
geeksforgeeks
Input : Hello!!!, he said ---and went.Output : Hello he said and went
A loop is designed that goes through a list composed of the characters
and punctuations of that string, removes the punctuation and then joins
them.

// Java program to remove punctuation from a given string


  
public class Test
{
    public static void main(String[] args)
    {
        // input string
        String str = "Welcome???@@##$ to#$% Geeks%$^for$
%^&Geeks";
          
        // similar to Matcher.replaceAll
        str = str.replaceAll("\\p{Punct}","");
          
        System.out.println(str);
    }
      
}
Output:
Welcome to GeeksforGeeks

Rearrange characters in a string such


that no two adjacent are same
Given a string with repeated characters, the task is to rearrange
characters in a string so that no two adjacent characters are same.
Note : It may be assumed that the string has only lowercase English
alphabets.
Examples:

Input: aaabc
Output: abaca

Input: aaabb
Output: ababa

Input: aa
Output: Not Possible

Input: aaaabc
Output: Not Possible
Prerequisite : priority_queue.
The idea is to put the highest frequency character first (a greedy
approach). We use a priority queue (Or Binary Max Heap) and put all
characters and ordered by their frequencies (highest frequency
character at root). We one by one take the highest frequency character
from the heap and add it to result. After we add, we decrease the
frequency of the character and we temporarily move this character out
of priority queue so that it is not picked next time.
We have to follow the step to solve this problem, they are:
1. Build a Priority_queue or max_heap, pq that stores characters and
their frequencies.
…… Priority_queue or max_heap is built on the bases of the frequency of
character.
2. Create a temporary Key that will be used as the previously visited
element (the previous element in the resultant string. Initialize it { char =
‘#’ , freq = ‘-1’ }
3. While pq is not empty.
….. Pop an element and add it to the result.
….. Decrease frequency of the popped element by ‘1’
….. Push the previous element back into the priority_queue if it’s
frequency > ‘0’
….. Make the current element as the previous element for the next
iteration.
4. If the length of the resultant string and original, print “not possible”.
Else print result.
Below is the implementation of above idea
// Java program to rearrange characters in a string
// so that no two adjacent characters are same.
import java.io.*;
import java.util.*;
  
class KeyComparator implements Comparator<Key> {
  
      // Overriding compare()method of Comparator
      public int compare(Key k1, Key k2)
      {
             if (k1.freq < k2.freq)
                 return 1;
             else if (k1.freq > k2.freq)
                 return -1;
             return 0;
      }
}
  
class Key {
      int freq; // store frequency of character
      char ch;
      Key(int val, char c) 
      {
          freq = val; 
          ch = c;
      }
}
  
class GFG {
      static int MAX_CHAR = 26; 
  
      // Function to rearrange character of a string
      // so that no char repeat twice
      static void rearrangeString(String str)
      {
             int n = str.length();
  
             // Store frequencies of all characters in string
             int[] count = new int[MAX_CHAR];
               
             for (int i = 0; i < n; i++)
                  count[str.charAt(i) - 'a']++;
  
              // Insert all characters with their frequencies
              // into a priority_queue 
              PriorityQueue<Key> pq = new PriorityQueue<>(new 
                                                          KeyC
omparator());
              for (char c = 'a'; c <= 'z'; c++) {
                   int val = c - 'a';
                   if (count[val] > 0)
                       pq.add(new Key(count[val], c));
              }
                   
              // 'str' that will store resultant value
              str = "" ;
  
              // work as the previous visited element
              // initial previous element be. ( '#' and
              // it's frequency '-1' )
              Key prev = new Key(-1, '#');
  
              // traverse queue
              while (pq.size() != 0) {
                
                     // pop top element from queue and add it
                     // to string.
                     Key k = pq.peek();
                     pq.poll();
                     str = str + k.ch;
  
                     // If frequency of previous character is
less
                     // than zero that means it is useless, we
                     // need not to push it 
                     if (prev.freq > 0)
                         pq.add(prev);
  
                     // make current character as the previous
'char'
                     // decrease frequency by 'one'
                     (k.freq)--;
                      prev = k;
              }
  
              // If length of the resultant string and
original
              // string is not same then string is not valid
              if (n != str.length())
                  System.out.println(" Not valid String ");
              else
                  System.out.println(str);
      }
  
      // Driver program to test above function 
      public static void main(String args[])
      {
             String str = "bbbaa" ;
             rearrangeString(str);
      }
}

Output:
babab
Time complexity : O(n)

Quick way to check if all the


characters of a string are same
Given a string, check if all the characters of the string are same or not.
Examples:
Input : s = "geeks"
Output : No

Input : s = "gggg"
Output : Yes
Simple Way

To find whether string has all the same characters. Traverse the whole
string from index 1 and check whether that character matches with first
character of string or not. If yes, than match until string size. If no, than
break the loop.
// Java program to find whether the String
// has all same characters or not.
import java.io.*;
  
public class GFG{
  
static boolean allCharactersSame(String s)
{
    int n = s.length();
    for (int i = 1; i < n; i++)
        if (s.charAt(i) != s.charAt(0))
            return false;
          
    return true;
}
  
// Driver code
    static public void main (String[] args){
        String s = "aaa";
    if (allCharactersSame(s))
        System.out.println("Yes");
    else
        System.out.println("No");
          
    }
}
  
Output:
Yes

Program to find the initials of a name.


Given a string name, we have to find the initials of the name
Examples:
Input : prabhat kumar singh
Output : P K S
We take the first letter of all
words and print in capital letter.

Input : Jude Law


Output : J L

Input : abhishek kumar singh


Output : A K S
1) Print first character in capital.
2) Traverse rest of the string and print every character after space in
capital letter.

// Java program to print initials of a name


class initials {
      
    static void printInitials(String name)
    {
        if (name.length() == 0)
            return;
  
        // Since touuper() returns int, 
        // we do typecasting
        System.out.print(Character.toUpperCase(
            name.charAt(0)));
  
        // Traverse rest of the string and 
        // print the characters after spaces.
        for (int i = 1; i < name.length() - 1; i++)
            if (name.charAt(i) == ' ')
                System.out.print(" " + Character.toUpperCase(
                                        name.charAt(i + 1)));
    }
  
    // Driver code
    public static void main(String args[])
    {
        String name = "prabhat kumar singh";
        printInitials(name);
    }
}
Output:
PKS
Another possible solution is given as follows:
// Java program to print initials of a name
class initials {
      
    static void printInitials(String name)
    {
        if (name.length() == 0)
            return;
  
        //split the string using 'space' 
        //and print the first character of every word
        String words[] = name.split(" ");
        for(String word : words) {
            System.out.print(Character.toUpperCase(word.charAt
(0)) + " ");
        }
    }
  
    // Driver code
    public static void main(String args[])
    {
        String name = "prabhat kumar singh";
        printInitials(name);
    }
}
Output:
PKS
The complexity of this code will be less than O(w) where w is number of
words in sentence, which can be little better than number of characters
in String.

Check Whether a number is Duck Number


or not
A Duck number is a number which has zeroes present in it, but there
should be no zero present in the beginning of the number. For example
3210, 8050896, 70709 are all duck numbers whereas 02364, 03401 are
not.
The task is to check whether the given number is a duck number or not.
Examples :
Input : 707069
Output : It is a duck number.
Explanation: 707069 does not contains zeros at the beginning.

Input : 02364
Output : It is not a duck number.
Explanation: in 02364 there is a zero at the beginning of the number.
// Java Program to check whether a 
// number is Duck Number or not.
  
import java.io.*;
class GFG
{
    // Function to check whether 
    // the given number is duck number or not.
    static int check_duck( String num)
    {
      // Length of the number(number of digits)
        int len = num.length(); 
        int count_zero = 0 ; 
        char ch;
   
        for(int i = 1;i < len ;i++)
        {
            // Checking for a digit whether it is a '0' or not
            ch=num.charAt(i); 
            if(ch=='0')
                count_zero++;
        }  
        return count_zero ;
    }
      
  
    // Driver Method
    public static void main(String args[])throws IOException
    {
        String num1 = "1023"; 
          
        // extracting the first digit
        char first_digit1 = num1.charAt(0); 
          
        // checking number1
        if( check_duck(num1) > 0 && first_digit1 != '0')
            System.out.println("It is a duck number");
        else
            System.out.println("It is not a duck number");
    }
}

Output :

It is a duck number.

Round the given number to nearest


multiple of 10
Given a positive integer n, round it to nearest whole number having zero
as last digit.
Examples:
Input : 4722
Output : 4720

Input : 38
Output : 40

Input : 10
Output: 10
Approach:
Let’s round down the given number n to the nearest integer which ends
with 0 and store this value in a variable a.
a = (n / 10) * 10. So, the round up n (call it b) is b = a + 10.
If n – a > b – n then the answer is b otherwise the answer is a.
Below is the implementation of the above approach:
// JAVA Code for Round the given number
// to nearest multiple of 10
import java.util.*;
  
class GFG {
      
    // function to round the number
    static int round(int n)
    {
        // Smaller multiple
        int a = (n / 10) * 10;
           
        // Larger multiple
        int b = a + 10;
       
        // Return of closest of two
        return (n - a > b - n)? b : a;
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
         int n = 4722;
         System.out.println(round(n));
    }
}
  
Output:
4720
Character Counting Based Problems :
Count Uppercase, Lowercase, special
character and numeric values
Given a string, write a program to count the occurrence of Lowercase
characters, Uppercase characters, Special characters and Numeric
values.
Examples:
Input : #GeeKs01fOr@gEEks07
Output :
Upper case letters : 5
Lower case letters : 8
Numbers : 4
Special Characters : 2

Input : *GeEkS4GeEkS*
Output :
Upper case letters : 6
Lower case letters : 4
Numbers : 1
Special Characters : 2
Approach :
Step 1: Scan a string str from 0 to length-1.
Step 2: check one character at a time on the basis of ASCII values
if(str[i] >= 65 and str[i] =97 and str[i] =48 and str[i] <=57) number
else special character
step 3: Print all the counters.

// Java program to count the uppercase,


// lowercase, special characters 
// and numeric values
import java.io.*;
  
class Count
{
    public static void main(String args[])
    {
        String str = "#GeeKs01fOr@gEEks07";
        int upper = 0, lower = 0, number = 0, special = 0;
  
        for(int i = 0; i < str.length(); i++)
        {
            char ch = str.charAt(i);
            if (ch >= 'A' && ch <= 'Z')
                upper++;
            else if (ch >= 'a' && ch <= 'z')
                lower++;
            else if (ch >= '0' && ch <= '9')
                number++;
            else
                special++;
        }
  
        System.out.println("Lower case letters : " + lower);
        System.out.println("Upper case letters : " + upper);
        System.out.println("Number : " + number);
        System.out.println("Special characters : " + special);
    }
}

Output:
Upper case letters: 5
Lower case letters : 8
Number : 4
Special characters : 2

Find the smallest window in a string


containing all characters of another
string
Given two strings string1 and string2, the task is to find the smallest
substring in string1 containing all characters of string2 efficiently.
Examples:
Input:  string = “this is a test string”, pattern = “tist”
Output:  Minimum window is “t stri”
Explanation:  “t stri” contains all the characters of pattern.
Input:  string = “geeksforgeeks”, pattern = “ork”
Output:  Minimum window is “ksfor”
Method 1 ( Brute force solution )
1- Generate all substrings of string1 (“this is a test string”)
2- For each substring, check whether the substring contains all
characters of string2 (“tist”)
3- Finally, print the smallest substring containing all characters of
string2.
 
Method 2 ( Efficient Solution )
1. First check if the length of string is less than the length of the
given pattern, if yes then “no such window can exist “.
2. Store the occurrence of characters of the given pattern in a
hash_pat[].
3. Start matching the characters of pattern with the characters of
string i.e. increment count if a character matches.
4. Check if (count == length of pattern ) this means a window is
found.
5. If such window found, try to minimize it by removing extra
characters from the beginning of the current window.
6. Update min_length.
7. Print the minimum length window.
Diagram to explain the above algorithm:

Below is the program to implement the above algorithm:


// Java program to find smallest window containing
// all characters of a pattern.
  
public class GFG 
{
    static final int no_of_chars = 256;
      
    // Function to find smallest window containing
    // all characters of 'pat'
    static String findSubString(String str, String pat)
    {
        int len1 = str.length();
        int len2 = pat.length();
      
        // check if string's length is less than pattern's
        // length. If yes then no such window can exist
        if (len1 < len2)
        {
            System.out.println("No such window exists");
            return "";
        }
      
        int hash_pat[] = new int[no_of_chars];
        int hash_str[] = new int[no_of_chars];
      
        // store occurrence ofs characters of pattern
        for (int i = 0; i < len2; i++)
            hash_pat[pat.charAt(i)]++;
      
        int start = 0, start_index = -1, min_len =
Integer.MAX_VALUE;
      
        // start traversing the string
        int count = 0; // count of characters
        for (int j = 0; j < len1 ; j++)
        {
            // count occurrence of characters of string
            hash_str[str.charAt(j)]++;
      
            // If string's char matches with pattern's char
            // then increment count
            if (hash_pat[str.charAt(j)] != 0 &&
                hash_str[str.charAt(j)] <=
hash_pat[str.charAt(j)] )
                count++;
      
            // if all the characters are matched
            if (count == len2)
            {
                // Try to minimize the window i.e., check if
                // any character is occurring more no. of
times
                // than its occurrence in pattern, if yes
                // then remove it from starting and also
remove
                // the useless characters.
                while ( hash_str[str.charAt(start)] >
hash_pat[str.charAt(start)]
                    || hash_pat[str.charAt(start)] == 0)
                {
      
                    if (hash_str[str.charAt(start)] >
hash_pat[str.charAt(start)])
                        hash_str[str.charAt(start)]--;
                    start++;
                }
      
                // update window size
                int len_window = j - start + 1;
                if (min_len > len_window)
                {
                    min_len = len_window;
                    start_index = start;
                }
            }
        }
      
        // If no window found
        if (start_index == -1)
        {
        System.out.println("No such window exists");
        return "";
        }
      
        // Return substring starting from start_index
        // and length min_len
        return str.substring(start_index, start_index +
min_len);
    }
      
    // Driver Method
    public static void main(String[] args)
    {
        String str = "this is a test string";
        String pat = "tist";
      
    System.out.print("Smallest window is :\n " +
                        findSubString(str, pat));
    }
}
Output:
Smallest window is :
t stri

Smallest window that contains all


characters of string itself
Given a string, find the smallest window length with all distinct
characters of the given string. For eg. str = “aabcbcdbca”, then the result
would be 4 as of the smallest window will be “dbca” .
Examples:
Input : aabcbcdbca
Output : dbca
Explanation :
dbca of length 4 is the smallest
window with highest number of distinct
characters.

Input : aaab
Output : ab
Explanation :
ab of length 2 is the smallest window
with highest number of distinct characters.
Above problem states that we have to find the smallest window that
contains all the distinct characters of the given string even if the smallest
string contains repeating elements.

For example, in “aabcbcdb”, the smallest string that contains all the
characters is “abcbcd”.
This problem reduces to Find the smallest window in a string containing
all characters of another string.
In that problem we find the smallest window that contains all the
characters of given pattern.
1- Count all distinct characters in given string.
2- Now follow the algorithm discussed in below post.
https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-
containing-all-characters-of-another-string/
We basically maintain a window of characters. Whenever the window
contains all characters of given string, we shrink the window from left
side to remove extra characters and then compare its length with
smallest window fount so far.
// Java program to find the smallest window containing
// all characters of a pattern.
import java.util.Arrays;
public class GFG {
  
    static final int MAX_CHARS = 256;
       
    // Function to find smallest window containing
    // all distinct characters
    static String findSubString(String str)
    {
        int n = str.length();
       
        // Count all distinct characters.
        int dist_count = 0;
          
        boolean[] visited = new boolean[MAX_CHARS];
        Arrays.fill(visited, false);
        for (int i=0; i<n; i++)
        {
            if (visited[str.charAt(i)] == false)
            {
                visited[str.charAt(i)] = true;
                dist_count++;
            }
        }
       
        // Now follow the algorithm discussed in below
        // post. We basically maintain a window of characters
        // that contains all characters of given string.
        // https://www.geeksforgeeks.org/find-the-smallest-
window-in-a-string-containing-all-characters-of-another-
string/ 
        int start = 0, start_index = -1;
        int min_len = Integer.MAX_VALUE;
       
        int count = 0;
        int[] curr_count =  new int[MAX_CHARS];
        for (int j=0; j<n; j++)
        {
            // Count occurrence of characters of string
            curr_count[str.charAt(j)]++;
       
            // If any distinct character matched,
            // then increment count
            if (curr_count[str.charAt(j)] == 1 )
                count++;
       
            // if all the characters are matched
            if (count == dist_count)
            {
                // Try to minimize the window i.e., check if
                // any character is occurring more no. of
times
                // than its occurrence in pattern, if yes
                // then remove it from starting and also
remove
                // the useless characters.
                while (curr_count[str.charAt(start)] > 1)
                {
                    if (curr_count[str.charAt(start)] > 1)
                        curr_count[str.charAt(start)]--;
                    start++;
                }
                  
                // Update window size
                int len_window = j - start + 1;
                if (min_len > len_window)
                {
                    min_len = len_window;
                    start_index = start;
                }
            }
        }
        // Return substring starting from start_index
        // and length min_len
        return str.substring(start_index,
start_index+min_len);
    }
       
    // Driver code
    public static void main(String args[])
    {
        String str = "aabcbcdbca";
        System.out.println("Smallest window containing all
distinct"
               + " characters is " + findSubString(str));
    }
}
Output:
Smallest window containing all distinct characters is
dbca

Count number of substrings with exactly


k distinct characters
Given a string of lowercase alphabets, count all possible substrings (not
necessarily distinct) that has exactly k distinct characters.
Examples:
Input: abc, k = 2
Output: 2
Possible substrings are {"ab", "bc"}

Input: aba, k = 2
Output: 3
Possible substrings are {"ab", "ba", "aba"}

Input: aa, k = 1
Output: 3
Possible substrings are {"a", "a", "aa"}
Method 1 (Brute Force)

If the length of string is n, then there can be n*(n+1)/2 possible


substrings. A simple way is to generate all the substring and check each
one whether it has exactly k unique characters or not. If we apply this
brute force, it would take O(n*n) to generate all substrings and O(n) to
do a check on each one. Thus overall it would go O(n*n*n).
Method 2
The problem can be solved in O(n*n). Idea is to maintain a hash table
while generating substring and checking the number of unique
characters using that hash table.
The implementation below assume that the input string contains only
characters from ‘a’ to ‘z’.
Implementation
// Java program to CountKSubStr number of substrings
// with exactly distinct characters in a given string
import java.util.Arrays;
  
public class CountKSubStr
{
    // Function to count number of substrings
    // with exactly k unique characters
    int countkDist(String str, int k)
    {
        // Initialize result
        int res = 0;
  
        int n = str.length();
  
        // To store count of characters from 'a' to 'z'
        int cnt[] = new int[26];
  
        // Consider all substrings beginning with
        // str[i]
        for (int i = 0; i < n; i++)
        {
            int dist_count = 0;
  
            // Initializing count array with 0
            Arrays.fill(cnt, 0);
  
            // Consider all substrings between str[i..j]
            for (int j=i; j<n; j++)
            {
                // If this is a new character for this
                // substring, increment dist_count.
                if (cnt[str.charAt(j) - 'a'] == 0)
                    dist_count++;
  
                // Increment count of current character
                cnt[str.charAt(j) - 'a']++;
  
                // If distinct character count becomes k,
                // then increment result.
                if (dist_count == k)
                    res++;
            }
        }
  
        return res;
    }
  
    // Driver Program
    public static void main(String[] args)
    {
        CountKSubStr ob = new CountKSubStr();
        String ch = "abcbaa";
        int k = 3;
        System.out.println("Total substrings with exactly " +
                           k +    " distinct characters : "
                           + ob.countkDist(ch, k));
    }
}
Output:
Total substrings with exactly 3 distinct characters : 8
Time Complexity : O(n*n)

Number of substrings of a string


Find total number of non-empty substrings of a string with N characters.
Here we use the word proper because we do not consider string itself as
part of output.
Input : str = “abc”
Output : 6
Proper substrings are “a”, “b”, “c”, “ab”, “bc”, “abc”
Input : str = “abcd”
Output : 10
Proper substrings are “a”, “b”, “c”, “d”, “ab”, “bc”, “cd”,
“abc”, “bcd” and “abcd”
Count of non-empty substrings is n*(n+1)/2
If we include empty string also as substring, the count becomes
n*(n+1)/2 + 1
How does above formula work?
1. Number of substrings of length one is n (We can choose any of the
n characters)
2. Number of substrings of length two is n-1 (We can choose any of
the n-1 pairs formed by adjacent)
3. Number of substrings of length three is n-2
(We can choose any of the n-2 triplets formed by adjacent)
4. In general, mumber of substrings of length k is n-k+1 where 1 <= k
<= n
Total number of substrings of all lengths from 1 to n =
n + (n-1) + (n-2) + (n-3) + … 2 + 1
= n * (n + 1)/2
// Java program to count number of substrings
// of a string
import java.io.*;
  
public class GFG {
      
    static int countNonEmptySubstr(String str)
    {
        int n = str.length();
        return n * (n + 1) / 2;
    }
      
    // Driver code
    public static void main(String args[])
    {
        String s = "abcde";
        System.out.println(
                  countNonEmptySubstr(s));
    }
}
Output:
15

Count words in a given string


Given a string, count number of words in it. The words are separated by
following characters: space (‘ ‘) or new line (‘\n’) or tab (‘\t’) or a
combination of these.
There can be many solutions to this problem. Following is a simple
and interesting solution.
The idea is to maintain two states: IN and OUT. The state OUT indicates
that a separator is seen. State IN indicates that a word character is seen.
We increment word count when previous state is OUT and next
character is a word character.
/* Java program to count no of words
from given input string. */
public class GFG {
   
    static final int OUT = 0;
    static final int IN = 1;
       
    // returns number of words in str
    static int countWords(String str)
    {
        int state = OUT;
        int wc = 0;  // word count
        int i = 0;
          
        // Scan all characters one by one
        while (i < str.length())
        {
            // If next character is a separator, set the 
            // state as OUT
            if (str.charAt(i) == ' ' || str.charAt(i) == '\n' 
                    || str.charAt(i) == '\t')
                state = OUT;
                  
       
            // If next character is not a word separator
            // and state is OUT, then set the state as IN
            // and increment word count
            else if (state == OUT)
            {
                state = IN;
                ++wc;
            }
       
            // Move to next character
            ++i;
        }
        return wc;
    }
       
    // Driver program to test above functions
    public static void main(String args[])
    {
        String str = "One two       three\n four\tfive  ";
        System.out.println("No of words : " +
countWords(str));
    }
}
Output:

No of words : 5
Time complexity: O(n)

Count words present in a string


Given an array of words and a string, we need to count all words that are
present in given string.
Examples:
Input : words[] = { "welcome", "to", "geeks", "portal"}
str = "geeksforgeeks is a computer science portal for
geeks."Output : 2
Two words "portal" and "geeks" is present in str.

Input : words[] = {"Save", "Water", "Save", "Yourself"}


str = "Save"Output :1

Steps:
1. Extract each word from string.
2. For each word, check if it is in word array(by creating set/map). If
present, increment result.
Below is the Java implementation of above steps
// Java program to count number 
// of words present in a string
  
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
public class Test 
{
    static int countOccurrence(String[] word, String str) 
    {
        // counter
        int counter = 0;
          
        // for extracting words
        Pattern p = Pattern.compile("[a-zA-Z]+");
        Matcher m = p.matcher(str);
          
        // HashSet for quick check whether
        //  a word in str present in word[] or not
        HashSet<String> hs = new HashSet<String>();
          
        for (String string : word) {
            hs.add(string);
        }
          
        while(m.find())
        {
            if(hs.contains(m.group()))
                counter++;
        }
          
        return counter;
          
    }
      
    public static void main(String[] args) 
    {
        String word[] = { "welcome", "to", "geeks", "portal"};
          
        String str = "geeksforgeeks is a computer science
portal for geeks.";
          
        System.out.println(countOccurrence(word,str));
          
    }
  
}

Output:
2

Reverse & Rotation :


Write a program to reverse an array or
string
Given an array (or string), the task is to reverse the array/string.
Examples :
Input : arr[] = {1, 2, 3}
Output : arr[] = {3, 2, 1}
Input : arr[] = {4, 5, 1, 2}
Output : arr[] = {2, 1, 5, 4}
Iterative way :

1) Initialize start and end indexes as start = 0, end = n-1


2) In a loop, swap arr[start] with arr[end] and change start
and end as follows :
start = start +1, end = end – 1

Another example to reverse a string:

Below is the implementation of the above approach :


// Iterative java program to reverse an
// array
public class GFG {
      
   /* Function to reverse arr[] from 
    start to end*/
    static void rvereseArray(int arr[],
                    int start, int end)
    {
        int temp;
           
        while (start < end)
        {
            temp = arr[start]; 
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        } 
    }     
       
    /* Utility that prints out an
    array on a line */
    static void printArray(int arr[], 
                            int size)
    {
        for (int i = 0; i < size; i++)
             System.out.print(arr[i] + " ");
           
         System.out.println();
    } 
  
    // Driver code
    public static void main(String args[]) {
          
        int arr[] = {1, 2, 3, 4, 5, 6};
        printArray(arr, 6);
        rvereseArray(arr, 0, 5);
        System.out.print("Reversed array is \n");
        printArray(arr, 6); 
         
    }
}
Output :
123456
Reversed array is
654321
Time Complexity : O(n)
Recursive Way :
1) Initialize start and end indexes as start = 0, end = n-1
2) Swap arr[start] with arr[end]
3) Recursively call reverse for rest of the array.
Below is the implementation of the above approach :
// Recursive Java Program to reverse an array
import java.io.*;
  
class ReverseArray {
  
    /* Function to reverse arr[] from start to end*/
    static void rvereseArray(int arr[], int start, int end)
    {
        int temp;
        if (start >= end)
            return;
        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        rvereseArray(arr, start+1, end-1);
    }
  
    /* Utility that prints out an array on a line */
    static void printArray(int arr[], int size)
    {
        for (int i=0; i < size; i++)
            System.out.print(arr[i] + " ");
        System.out.println("");
    }
  
    /*Driver function to check for above functions*/
    public static void main (String[] args) {
        int arr[] = {1, 2, 3, 4, 5, 6};
        printArray(arr, 6);
        rvereseArray(arr, 0, 5);
        System.out.println("Reversed array is ");
        printArray(arr, 6);
    }
}
Output :
123456
Reversed array is
654321
Time Complexity : O(n)

Reverse individual words


Given a string str, we need to print reverse of individual words.
Examples:
Input : Hello World
Output : olleH dlroW

Input : Geeks for Geeks


Output : skeeG rof skeeG
Method 1 (Simple): Generate all words separated by space. One by one
reverse words and print them separated by space.
Method 2 (Space Efficient): We use a stack to push all words before
space. As soon as we encounter a space, we empty the stack.
// Java program to reverse individual 
// words in a given string using STL list
import java.io.*;
import java.util.*;
  
class GFG {
  
// reverses individual words of a string
static void reverseWords(String str)
{
    Stack<Character> st=new Stack<Character>();
   
    // Traverse given string and push all
    // characters to stack until we see a space.
    for (int i = 0; i < str.length(); ++i) {
        if (str.charAt(i) != ' ')
            st.push(str.charAt(i));
   
        // When we see a space, we print
        // contents of stack.
        else {
            while (st.empty() == false) {
                System.out.print(st.pop());
                  
            }
            System.out.print(" ");
        }
    }
   
    // Since there may not be space after
    // last word.
    while (st.empty() == false) {
        System.out.print(st.pop());
          
    }
}
  
// Driver program to test above function
public static void main(String[] args)
{
   String str = "Geeks for Geeks";
    reverseWords(str);
  }
}

Output:
skeeG rof skeeG

Print words of a string in reverse


order
Let there be a string say “I AM A GEEK”. So, the output should be “GEEK
A AM I” . This can done in many ways. One of the solutions is given
in Reverse words in a string .
Examples:
Input : I AM A GEEK
Output : GEEK A AM I

Input : GfG IS THE BEST


Output : BEST THE IS GfG

This can be done in more simpler way by using the property of the “%s
format specifier” .

Property: %s will get all the values until it gets NULL i.e. ‘\0’.
Example: char String[] = “I AM A GEEK” is stored as shown in the image
below :

Approach: Traverse the string from the last character, and move


towards the first character. While traversing, if a space character is
encountered, put a NULL in that position and print the remaining string
just after the NULL character. Repeat this until the loop is over and when
the loop ends, print the string, the %s will make the printing of
characters until it encounters the first NULL character.
Let us see the approach with the help of diagrams:
step 1: Traverse from the last character until it encounters a space
character .
Step 2: Put a NULL character at the position of space character and print
the string after it.

Step 3: At the end, the loop ends when it reaches the first character, so
print the remaining characters, it will be printed the first NULL character,
hence the first word will be pprinted.

// java program to print reverse 


// of words in a string.
import java.io.*;
import java.util.*;
import java.lang.*;
  
class GFG
{
static String wordReverse(String str)
{
    int i = str.length() - 1;
    int start, end = i + 1;
    String result = "";
      
    while(i >= 0)
    {
        if(str.charAt(i) == ' ')
        {
            start = i + 1;
            while(start != end)
                result += str.charAt(start++);
              
            result += ' ';
              
            end = i;
        }
        i--;
    }
      
    start = 0;
    while(start != end)
        result += str.charAt(start++);
      
    return result;
}
  
// Driver code
public static void main(String[] args)
{
    String str = "I AM A GEEK";
      
    System.out.print(wordReverse(str));
}
}
  
Output:
GEEK A AM I

Print reverse of a string using


recursion
Write a recursive function to print reverse of a given string.

Program:
// Java program to reverse a string using recursion
  
class StringReverse
{
    /* Function to print reverse of the passed string */
    void reverse(String str)
    {
        if ((str==null)||(str.length() <= 1))
           System.out.println(str);
        else
        {
            System.out.print(str.charAt(str.length()-1));
            reverse(str.substring(0,str.length()-1));
        }
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
        String str = "Geeks for Geeks";
        StringReverse obj = new StringReverse();
        obj.reverse(str);
    }    
}

Output:
skeeG rof skeeG

Explanation: Recursive function (reverse) takes string pointer (str) as


input and calls itself with next location to passed pointer (str+1).
Recursion continues this way, when pointer reaches ‘\0’, all functions
accumulated in stack print char at passed location (str) and return one
by one.

Time Complexity: O(n)

Minimum rotations required to get the


same string
Given a string, we need to find the minimum number of rotations
required to get the same string.
Examples:
Input : s = "geeks"
Output : 5

Input : s = "aaaa"
Output : 1
The idea is based on below post.
A Program to check if strings are rotations of each other or not

Step 1 : Initialize result = 0 (Here result is count of rotations)


Step 2 : Take a temporary string equals to original string concatenated
with itself.
Step 3 : Now take the substring of temporary string of size same as
original string starting from second character (or index 1).
Step 4 : Increase the count.
Step 5 : Check whether the substring becomes equal to original string. If
yes, then break the loop. Else go to step 2 and repeat it from the next
index.
// Java program to determine minimum number
// of rotations required to yield same
// string.
  
import java.util.*;
  
class GFG
{
    // Returns count of rotations to get the
    // same string back.
    static int findRotations(String str)
    {
        // tmp is the concatenated string.
        String tmp = str + str;
        int n = str.length();
      
        for (int i = 1; i <= n; i++)
        {
      
            // substring from i index of original
            // string size.
              
            String substring = tmp.substring(i, str.length());
      
            // if substring matches with original string
            // then we will come out of the loop.
            if (str == substring)
                return i;
        }
        return n;
    }
  
    // Driver Method
    public static void main(String[] args)
    {
            String str = "abc";
        System.out.println(findRotations(str));
    }
}
/* This code is contributed by Mr. Somesh Awasthi */

Output:
3
Time Complexity: O(n2)

Left Rotation and Right Rotation of a


String
Given a string of size n, write functions to perform following operations
on string.
1. Left (Or anticlockwise) rotate the given string by d elements
(where d <= n)
2. Right (Or clockwise) rotate the given string by d elements (where
d <= n).
Examples:
Input : s = "GeeksforGeeks"
d=2
Output : Left Rotation : "eksforGeeksGe"
Right Rotation : "ksGeeksforGee"

Input : s = "qwertyu"
d=2
Output : Left rotation : "ertyuqw"
Right rotation : "yuqwert"
A Simple Solution is to use a temporary string to do rotations. For left
rotation, first copy last n-d characters, then copy first d characters in
order to the temporary string. For right rotation, first copy last d
characters, then copy n-d characters.
Can we do both rotations in-place and O(n) time?
The idea is based on reversal algorithm for rotation.
// Left rotate string s by d (Assuming d <= n)leftRotate(s, d)
reverse(s, 0, d-1); // Reverse substring s[0..d-1]
reverse(s, d, n-1); // Reverse substring s[d..n-1]
reverse(s, 0, n-1); // Reverse whole string.

// Right rotate string s by d (Assuming d <= n)rightRotate(s, d)

// We can also call above reverse steps


// with d = n-d.
leftRotate(s, n-d)
Below is the implementation of above steps :
// Java program for Left Rotation and Right 
// Rotation of a String 
import java.util.*;
import java.io.*;
  
class GFG 
{
          
    // function that rotates s towards left by d 
    static String leftrotate(String str, int d)
    {
            String ans = str.substring(d) + str.substring(0,
d);
            return ans;
    }
  
    // function that rotates s towards right by d 
    static String rightrotate(String str, int d)
    {
            return leftrotate(str, str.length() - d);
    }
  
    // Driver code
    public static void main(String args[])
    {
            String str1 = "GeeksforGeeks"; 
            System.out.println(leftrotate(str1, 2));
  
            String str2 = "GeeksforGeeks"; 
            System.out.println(rightrotate(str2, 2)); 
    }
}
Output:
Left rotation: eksforGeeksGe
Right rotation: ksGeeksforGee

Sorting & Searching :

Sort an array of strings according to


string lengths
We are given an array of strings, we need to sort the array in increasing
order of string lengths.
Examples:
Input : {"GeeksforGeeeks", "I", "from", "am"}Output : I am from
GeeksforGeeks
Input : {"You", "are", "beautiful", "looking"}Output : You are looking
beautiful
A simple solution is to write our own sort function that compares string
lengths to decide which string should come first. Below is the
implementation that uses Insertion Sort to sort the array.

// Java program to sort an Array of 


// Strings according to their lengths
import java.util.*;
  
class solution
{
  
// Function to print the sorted array of string
// void printArraystring(string,int);
  
// Function to Sort the array of string
// according to lengths. This function 
// implements Insertion Sort. 
static void sort(String []s, int n)
{
    for (int i=1 ;i<n; i++)
    {
        String temp = s[i];
  
        // Insert s[j] at its correct position
        int j = i - 1;
        while (j >= 0 && temp.length() < s[j].length())
        {
            s[j+1] = s[j];
            j--;
        }
        s[j+1] = temp;
    }
}
  
// Function to print the sorted array of string
static void printArraystring(String str[], int n)
{
    for (int i=0; i<n; i++)
        System.out.print(str[i]+" ");
}
  
// Driver function
public static void main(String args[])
{
    String []arr = {"GeeksforGeeks", "I", "from", "am"};
    int n = arr.length;
      
    // Function to perform sorting
    sort(arr,n);
    // Calling the function to print result
    printArraystring(arr, n);
      
}
}

Output:
I am from GeeksforGeeks

Sort string of characters


Given a string of lowercase characters from ‘a’ – ‘z’. We need to write a
program to print the characters of this string in sorted order.
Examples:
Input : bbccdefbbaa
Output : aabbbbccdef

Input : geeksforgeeks
Output : eeeefggkkorss
// Java program to sort a string of characters 
  
import java.util.Arrays;
  
class GFG {
  
// function to print string in sorted order 
    static void sortString(String str) {
        char []arr = str.toCharArray();
        Arrays.sort(arr);
        System.out.print(String.valueOf(arr));
    }
  
// Driver program to test above function 
    public static void main(String[] args) {
        String s = "geeksforgeeks";
        sortString(s);
    }
}
Output:
eeeefggkkorss
Time Complexity: O(n log n), where n is the length of string.
An efficient approach will be to observe first that there can be a total of
26 unique characters only. So, we can store the count of occurrences of
all the characters from ‘a’ to ‘z’ in a hashed array. The first index of the
hashed array will represent character ‘a’, second will represent ‘b’ and
so on. Finally, we will simply traverse the hashed array and print the
characters from ‘a’ to ‘z’ the number of times they occurred in input
string.
Below is the implementation of above idea:
// Java program to sort 
// a string of characters
import java.util.Arrays;
import java.util.Collections;
  
class GFG 
{
    // Method to sort a 
    // string alphabetically
    public static String sortString(String inputString)
    {
        // convert input 
        // string to char array
        char tempArray[] = 
             inputString.toCharArray();
          
        // sort tempArray
        Arrays.sort(tempArray);
          
        // return new sorted string
        return new String(tempArray);
    }
      
    // Driver Code
    public static void main(String[] args)
    {
        String inputString = "geeksforgeeks";
          
        System.out.println(sortString(inputString));
    }
}
Output:
eeeefggkkorss
Time Complexity: O( n ), where n is the length of input string.
Auxiliary Space: O( 1 ).

Program to sort string in descending


order
Given a string, sort it in descending order.
Examples:
Input : alkasingh
Output : snlkihgaa

Input : nupursingh
Output : uusrpnnihg
Input : geeksforgeeks
Output : ssrokkggfeeee
// Java program to sort a string in descending
// order using library function
import java.util.*;
  
class GFG 
{
  
    static void descOrder(char[] s) 
    {
        Arrays.sort(s);
        reverse(s);
    }
  
    static void reverse(char[] a) 
    {
        int i, n = a.length;
        char t;
        for (i = 0; i < n / 2; i++) 
        {
            t = a[i];
            a[i] = a[n - i - 1];
            a[n - i - 1] = t;
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
        char[] s = "geeksforgeeks".toCharArray();
        descOrder(s); // function call
        System.out.println(String.valueOf(s));
    }
}
  
Output:
ssrokkggfeeee
The time complexity is : O(n log n)
An efficient approach will be to observe first that there can be a total of
26 unique characters only. So, we can store the count of occurrences of
all the characters from ‘a’ to ‘z’ in a hashed array. The first index of the
hashed array will represent character ‘a’, second will represent ‘b’ and
so on. Finally, we will simply traverse the hashed array and print the
characters from ‘z’ to ‘a’ the number of times they occurred in input
string.
Below is the implementation of above idea:
// Java program to sort a string of characters 
// in descending order 
  
class GFG
{
  
    static int MAX_CHAR = 26;
  
    // function to print string in sorted order 
    static void sortString(String str) 
    {
          
        // Hash array to keep count of characters. 
        // Initially count of all charters is 
        // initialized to zero. 
        int charCount[] = new int[MAX_CHAR];
  
        // Traverse string and increment 
        // count of characters 
        // 'a'-'a' will be 0, 'b'-'a' will be 1, 
        for (int i = 0; i < str.length(); i++) 
        {
              
            // so for location of character in count 
            // array we wil do str[i]-'a'. 
            charCount[str.charAt(i) - 'a']++;
        }
  
        // Traverse the hash array and print 
        // characters 
        for (int i = MAX_CHAR - 1; i >= 0; i--)
        {
            for (int j = 0; j < charCount[i]; j++) 
            {
                System.out.print((char) ('a' + i));
            }
        }
    }
  
    // Driver code 
    public static void main(String[] args)
    {
        String s = "alkasingh";
        sortString(s);
    }

Output:
snlkihgaa
Time Complexity: O( n ), where n is the length of input string.
Auxiliary Space: O( 1 ).

Potrebbero piacerti anche