Friday, June 4, 2021

String Handling in Java

Strings in Handling in Java

 A String is a standard object in Java of Class String and is provided built-in support. A String is sequence of characters. A String is a final class in Java (it can not be further extended) and the objects of this class are immutable(means these are read-only). The String class’s objects support for +,+=(concatenation) operators. The String class objects are thread-safe. We can use StringBuffer and StringBuilder classes for using a mutable string.

The ability to manipulate alphanumeric data (such as names, addresses, text, etc.) is called String handling. Several methods are provided in String class to handle strings. Few Examples of string handling are listed below along with their solutions.

1. Reverse a given String

Test Case

Input: Hello

Output: olleH

Solution:

import java.util.Scanner;

public class Q1 {
//1.Reverse a given String.
	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		System.out.println("Enter some string");
		String s=scan.nextLine();
		StringBuffer sb=new StringBuffer(s);
		String rev=sb.reverse().toString();
		/* Another way to do the same thing
		 * char str[]=s.toCharArray();
		System.out.println("reverse string is:");
		for(int i=s.length()-1;i>=0;i--)
		{
			System.out.print(str[i]);
		}*/
		System.out.println(rev);
	}

}



2. Find the maximum occurring(highest frequency) character in a given String.(ignore case)

Input: Godzilla

Output: L 2

Solution:

import java.util.Scanner;

public class Q2 {
//2.	Find the maximum occurring character in a given String.
	public static void main(String[] args) {
		int arr[]=new int[26];
		Scanner scan=new Scanner(System.in);
		System.out.println("Enter some string");
		String s=scan.nextLine();
		char strarr[]=s.toUpperCase().toCharArray();
		for(char c:strarr)
		{
			if((int)c>=65 && (int)c<90)
			{
			arr[(int)c-65]++;
			}
		}
		int max=0;
		char ch='$';
		for(int j=0;j<arr.length;j++)
		{
			if(arr[j]>max)
			{
				max=arr[j];
				ch=(char)(j+65);
			}
		}
		System.out.println(max+"  "+ch);
		scan.close();
	}

}


3. Remove all duplicates from a given string. (ignore case)

Input : Godzilla

Output: GODZILA

Solution:

import java.util.HashSet;
import java.util.Scanner;
import java.util.TreeSet;

public class Q3 {

	public static void main(String[] args) {
		//3.	Remove all duplicates from a given string.
		//hello
		//helo
		Scanner scan=new Scanner(System.in);
		System.out.println("Enter some string");
		String s=scan.nextLine();
		TreeSet<Character> hs=new TreeSet<>();
		char[] ch=s.toUpperCase().toCharArray();
		for(char c:ch)
		{
			hs.add(c);
		}
		System.out.println("Output");
		for(Character c:hs)
		{
			System.out.print(c);
		}
	}

}


4. Print the unique characters from the given String. (ignore case)

Input : Godzilla

Output: GODZILA

Solution:

import java.util.Scanner;

public class Q4 {
//4.	Print the unique characters from the given String.
	
	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		System.out.println("Enter some string");
		String s=scan.nextLine();
		char[] ch=s.toCharArray();
		//{h,e,l,l,o}
		//{h,e,l,$,o}
		for(int i=0;i<ch.length;i++)
		{
			for(int j=i+1;j<ch.length;j++)
			{
				if(ch[i]==ch[j] && ch[i]!='$')
				{
					ch[j]='$';
				}
			}
		}
		System.out.println("unique characters are:");
		for(int i=0;i<ch.length;i++)
		{
			if(ch[i]!='$')
			System.out.print(ch[i]);
		}
	}

}



5. How to print all permutations of a String. (ignore case)

Input: abb

Output: abb abb bab bba bab bba 

Solution:

import java.util.HashSet;
import java.util.Scanner;

public class Q5 {
	// Function to print all the permutations of str
    static void printPermutn(String str, String ans)
    {
  
        // If string is empty
        if (str.length() == 0) {
            System.out.print(ans + " ");
            return;
        }
  
        for (int i = 0; i < str.length(); i++) {
  
            // ith character of str
            char ch = str.charAt(i);
  
            // Rest of the string after excluding 
            // the ith character
            String ros = str.substring(0, i) + 
                         str.substring(i + 1);
  
            // Recurvise call
            printPermutn(ros, ans + ch);
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String s = "abb";
        printPermutn(s, "");
    }
	

}


6. Reverse the words in a given String sentence.

Input: I am not an alien

Output: alien an not am I

Solution:

import java.util.Scanner;

public class Q6 {
	//6.Reverse the words in a given String sentence.
	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		System.out.println("Enter some string");
		String s=scan.nextLine();
		String[] strs=s.split(" ");
		for(int i=strs.length-1;i>=0;i--)
		{
			System.out.println(strs[i]);
		}
		scan.close();
	}

}


7. Check if a given String is Palindrome or not.

Input: malayalam

Output: Palindrome

Solution:

import java.util.Scanner;

public class Q7 {
//7. Check if a given String is Palindrome or not.
	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		System.out.println("Enter some string");
		String s=scan.nextLine();
		StringBuffer sb=new StringBuffer(s);
		String rev=sb.reverse().toString();
		if(s.equals(rev))
		{
			System.out.println("palindrome");
		}else
		{
			System.out.println("not palindrome");
				
		}
	}

}


8. Check if two Strings are anagrams of each other. (An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once)

Input: Army Mary

Output: Anagram

Solution:

import java.util.Arrays;
import java.util.Scanner;
import java.util.TreeSet;

public class Q8 {
//8. check if two Strings are anagrams of each other
	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		System.out.println("Enter first string");
		String s1=scan.nextLine();
		System.out.println("Enter second string");
		String s2=scan.nextLine();
		char[] arr1=s1.toUpperCase().toCharArray();
		char[] arr2=s2.toUpperCase().toCharArray();
		Arrays.sort(arr1);
		Arrays.sort(arr2);
		if(arr1.length!=arr2.length)
		{
			System.out.println("Not anagrams");
			return;
		}
		else
		{
			for(int i=0;i<arr1.length;i++)
			{
			if(arr1[i]!=arr2[i])
			{
				System.out.println("Not anagrams");
				return;
			}
			}
			System.out.println("Anagrams");
		}

		scan.close();

	}

}


9. Sort array(read arrays in Java) of Strings in alphabetic order.

Input: mango apple orange papaya lemon

Output: apple lemon mango orange papaya


Solution:

import java.util.Arrays;

public class Q9 {
//9.Sort array of Strings
	public static void main(String[] args) {
		String[] str= {"mango","apple","orange","papaya","lemon"};
		Arrays.sort(str);
		for(String s:str)
		{
			System.out.print(s);
		}
	}
}