Skip to content

Commit c1222ab

Browse files
committed
Added Programs on String - under #1
1 parent 1d6e663 commit c1222ab

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

Strings/Anagram.java

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
3+
Q: Write a java program to check whether two strings are anagram or not.
4+
Explaination: An anagram is a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman.
5+
6+
Sample Input: Listen, Silent
7+
Sample Output: Anagram
8+
9+
Sample Input: Tic, Tac
10+
Sample Output: Not Anagram
11+
12+
*/
13+
14+
import java.util.Scanner;
15+
import java.util.Arrays;
16+
17+
public class Anagram
18+
{
19+
public static void main(String[] args) {
20+
Scanner scan = new Scanner(System.in);
21+
System.out.println("Enter first string:");
22+
String str1 = scan.nextLine();
23+
System.out.println("Enter second string:");
24+
String str2 = scan.nextLine();
25+
// Initially checking if the length of both strings are same or not if not then printing not anagram and exiting the program
26+
if(str1.length() != str2.length()) {
27+
System.out.println("Not Anagram");
28+
System.exit(0);
29+
}
30+
//If the length of both strings are same then converting both strings to lower case character array and sorting them
31+
char []arr1 = str1.toLowerCase().toCharArray();
32+
char []arr2 = str2.toLowerCase().toCharArray();
33+
Arrays.sort(arr1);
34+
Arrays.sort(arr2);
35+
//Comparing the sorted arrays and printing the result
36+
if(Arrays.equals(arr1, arr2)) {
37+
System.out.println("Anagram");
38+
}
39+
else {
40+
System.out.println("Not Anagram");
41+
}
42+
}
43+
}

Strings/Palindrome.java

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
3+
Q: Write a java program to check if a given string is a palindrome or not.
4+
5+
Sample Input: malayalam
6+
Sample Output: Entered string is a palindrome.
7+
8+
*/
9+
10+
import java.util.Scanner;
11+
12+
public class Palindrome {
13+
//Method to check if the given string is palindrome or not
14+
static void checkPalindrome(String str) {
15+
String revstr = "";
16+
// Loop for reversing the string
17+
for(int i = str.length()-1; i >= 0; i--) {
18+
revstr += str.charAt(i);
19+
}
20+
// Condition checking if the reversed string is equals to main string or not
21+
if(str.equalsIgnoreCase(revstr)) {
22+
System.out.println("Entered string is a palindrome");
23+
}
24+
else {
25+
System.out.println("Entered string is not a palindrome");
26+
}
27+
}
28+
// Main method
29+
public static void main(String[] args) {
30+
Scanner scan = new Scanner(System.in);
31+
System.out.println("Enter a string: ");
32+
String str = scan.next();
33+
checkPalindrome(str);
34+
scan.close();
35+
}
36+
}

0 commit comments

Comments
 (0)