Module-3: Strings
1. Write a Java program to reverse each word in a given sentence while maintaining the order
of words.
2. Write a Java program to check if two given strings are anagrams. Two strings are anagrams
if they contain the same characters in the same frequency, but in a different order (ignoring
spaces and case sensitivity).
1. Write a Java program to reverse each word in a given sentence while maintaining the order
of words.
import java.util.Scanner;
public class M3_1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the sentence : ");
String s1 = scanner.nextLine();
String[] s2=s1.split(" ");
for(String a:s2) //for each loop
{
StringBuffer sb = new StringBuffer(a);
sb.reverse();
String rs = sb.toString();
System.out.print(rs+" ");
}
}
}
Output:
2. Write a Java program to check if two given strings are anagrams. Two strings are anagrams
if they contain the same characters in the same frequency, but in a different order (ignoring
spaces and case sensitivity).
import java.util.*;
public class M3_2
{
public static void main(String[] args)
{
//1.Read the strings using scanner class
System.out.println("Enter the first string");
Scanner input1=new Scanner(System.in);
String s1=input1.nextLine();
System.out.println("Enter the second string");
Scanner input2=new Scanner(System.in);
String s2=input2.nextLine();
//2.Not a Anagrams if Lengths are not equal
if(s1.length()!=s2.length())
{
System.out.println("Not an Anagrams");
}
else
{
//3.Convert the strings into lowercase
String s11=s1.toLowerCase();
String s22=s2.toLowerCase();
//4.Convert the strings into characters
char[] arr1 = s11.toCharArray();
char[] arr2 = s22.toCharArray();
// 5. Sort the char array
Arrays.sort(arr1);
Arrays.sort(arr2);
//6.Convert characters into string
String sb1=new String(arr1);
String sb2=new String(arr2);
System.out.println(sb1);
System.out.println(sb2);
//7.check the Equivalence of two strings
if(sb1.equals(sb2))
{
System.out.println("The given strings are Anagrams");
}
else
{
System.out.println("The given strings not Anagrams");
}
}
}
Output: