1) : Write a Java Program to reverse a string without using String inbuilt function.
Answer: There are several ways to achieve this, We will look 3 ways to achieve this:
Method 1: By using CharArray[] , we can convert string into CharArray[] and then print that string in reverse order using index.
public class ReverseStringWithoutInbuildFunction {
public static void main(String[] args) {
String name= "Tanuja";
char chars[] = name.toCharArray(); // converted to character array and printed in reverse order
for(int i= chars.length-1; i>=0; i--) {
System.out.print(chars[i]);
}
}
}
Output: ajunaTMethod 2: Using split function, to split string into its substrings(no delimeter is used here)and then print string in reverse order.
public static void main(String[] args) {
String str = "corejava";
String[] token = str.split(""); //used split method to print in reverse order
for(int i=token.length-1; i>=0; i--)
{
System.out.print(token[i] + "");
}
}Output: avajeroc
Method 3: Using CharAt() function, its similar to method 1 but instead of using charArray[], we can use charAt() function:
public static void main(String[] args) {
String str = "corejava";
String reverse = "";
int length = str.length();
for(int i=length-1; i>=0; i--) {
reverse = reverse + original.charAt(i); //used inbuilt method charAt() to reverse the string
}
System.out.println(reverse);
}
2) How to find the maximum occurring character in given String?Answer: In below code, I used 2 approaches:
1. Using for loop, taking count of character which we want to find out.
2. Using HashMap , we can keep all characters and their counts/occurrences information.
3. Using Replace() method of string, we can remove character from original string then calculate length of string. Please refer code :
package javaBasics;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class StringMaxOccurence {
public static void main(String[] args) {
String input = "aashish"; // count number of "a" on this String.
// counting occurrence of character with loop
int charCount = 0;
for (char ch : input.toCharArray()) {
if (ch == 'a') {
charCount++;
}
}
System.out.println("Occurence of 'a' in given input: " + charCount);
// Using HashMp count the ocuurence
char[] characters = input.toCharArray(); // convert string to char[]
Map<Character, Integer> charMap = new HashMap<Character, Integer>();
for (Character ch : characters) {
if (charMap.containsKey(ch)) {
charMap.put(ch, charMap.get(ch) + 1);
} else {
charMap.put(ch, 1);
}
}
// Iterate through HashMap to print all duplicate characters of String
Set<Map.Entry<Character, Integer>> entrySet = charMap.entrySet();
System.out.println("List of duplicate characters in String : " + input);
for (Map.Entry<Character, Integer> entry : entrySet) {
if (entry.getValue() > 1) {
System.out.printf("%s : %d %n", entry.getKey(), entry.getValue());
}
}
//Using Replace Method we can finf occurrence of characters.
String s = "Java is java"; char c = 'a'; int count = s.length() - s.replace("a", "").length(); System.out.println("Number of occurances of 'a' in :"+s+" is = "+count);
}
}
Output: Occurence of 'a' in given input: 2 List of multiple occurences of below characters in String : aashish a : 2 s : 2 h : 2
Number of occurances of 'a' in :Java is java is = 4
3) : How to check if two Strings are anagrams of each other?Answer: Two strings are anagrams if they are written using the same exact letters. for example "stop" and "tops" both strings are anagram, as they are written exactly using same letters. To achieve this, we can take character from first given string and then remove the occurrence of that character from second string and update second string with latest value, likewise till end of first string and finally if we get empty string then both strings are exactly using same characters, so they are anagram. To achieve this, we can use substring method of string. till Java 6 substring() method causes memory leak issues but on java 7 onward that issue got resolved.
package javaBasics;
public class StringAnagram {
public static void main(String[] args) {
String originalString = "stop";
String anagramString = "tops";
if (isAnagram(originalString, anagramString)) {
System.out.println("String is Anagram");
} else {
System.out.println("String is not Anagram");
}
}
public static boolean isAnagram(String word, String anagram) {
if (word.length() != anagram.length()) {
return false;
}
char[] chars = word.toCharArray();
for (char c : chars) {
int index = anagram.indexOf(c);
if (index != -1) {
// Remove c (character of word) from anagram e.g. in first iteration remove 's'
// from 'stop' so output is: top
anagram = anagram.substring(0, index) + anagram.substring(index + 1, anagram.length());
System.out.println("Updated anagram is =" + anagram);
} else {
return false;
}
}
return anagram.isEmpty();
}
}
output: anagram =top
anagram =op
anagram =p
anagram =
String is Anagram
4) : How to reverse String in Java?
Answer: There are 3 ways to reverse string:
1) Using StringBuffer class:
In this method, we use reverse() method of StringBuffer class to reverse the string.
2) Using iterative method:
In this method, first we convert given string to char array using charArray() method. And then we iterate that array in the reverse order.
3) Using recursive method:
In this method, reverses the string by calling itself recursively.
package javaBasics;
public class ReverseTheString5) How To Find All Permutations Of String In Java?
{
public static void main(String[] args)
{
String str = "MyJava";
//1. Using StringBuffer Class
StringBuffer sbf = new StringBuffer(str);
System.out.println(sbf.reverse()); //Output : avaJyM
//2. Using iterative method
char[] strArray = str.toCharArray();
for (int i = strArray.length - 1; i >= 0; i--)
{
System.out.print(strArray[i]); //Output : avaJyM
}
System.out.println();
//3. Using Recursive Method
System.out.println(recursiveMethod(str)); //Output : avaJyM
}
//Recursive method to reverse string
static String recursiveMethod(String str)
{
if ((null == str) || (str.length() <= 1))
{
return str;
}
return recursiveMethod(str.substring(1)) + str.charAt(0);
}
}
Solution:
package StringExamples;
public class StringPermutations {
static public void StringPermutation(String input)
{
StringPermutation("", input);
}
private static void StringPermutation(String permutation, String input)
{
if(input.length() == 0)
{
System.out.println(permutation);
}
else
{
for (int i = 0; i < input.length(); i++)
{
StringPermutation(permutation+input.charAt(i), input.substring(0, i)+input.substring(i+1, input.length()));
}
}
}
public static void main(String[] args) {
StringPermutation("ten");
}
}Output:
ten
tne
etn
ent
nte
net
6) How to swap two strings without using third variable in Java?
Solution: Here we are using substring() method to swap two strings.
public class SwapTwoStrings{7) Write program to sort two strings lexicographically, calulate length of two strings and
public static void main(String[] args)
{
String s1 ="core";
String s2 "java"
System.out.println("Before Swapping :");
System.out.println("s1 : "+s1);
System.out.println("s2 : "+s2);
s1 = s1 + s2;
s2 = s1.substring(0, s1.length()-s2.length());
s1 = s1.substring(s2.length());
System.out.println("After Swapping :");
System.out.println("s1 : "+s1);
System.out.println("s2 : "+s2);
}
}
print first letter of each string in capital format?
Solution: Refer below Example -
1. String is "hello" and is "java", has a length and the sum of their lengths is 9.
2. When sorted alphabetically/lexicographically, "hello" precedes "java"; therefore, is not greater than and the answer is No.
3. When you capitalize the first letter of both and and then print them separated by a space, you get "Hello Java".
To sort strings lexicographical, here we used comapreTo() method of string.
import java.io.*;import java.util.*;8)Find all possible subtsrings from given input string and lengh of substring,
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String A=sc.next();
String B=sc.next();
/* Enter your code here. Print output to STDOUT. */
int totalLength = A.length() + B.length();
System.out.println(totalLength);
if(A.compareTo(B) > 0){
System.out.println("Yes");
}else{
System.out.println("No");
}
String updatedA = A.substring(0,1).toUpperCase()+ A.substring(1);
String updatedB = B.substring(0,1).toUpperCase()+ B.substring(1);
String finalString = updatedA +" " +updatedB;
System.out.println(finalString);
}
}
After that among all substrings find the first/small and last/large strings which are lexicographically sorted
Solution:
public static void main(String[] args) {
findSmallestLargestSubstring("corejava", 3);
}
public static String findSmallestLargestSubstring(String s, int k)
{
String smallest, largest ="";
ArrayList<String> list = new ArrayList<String>();
String temp;
for (int i = 0; i < s.length(); i++) {
int length = i +3;
if(length <= s.length()) {
list.add(s.substring(i, i+3));
}
else {
break;
}
}
Collections.sort(list);
int length = list.size();
smallest = list.get(0);
largest = list.get(length -1);
return smallest + "\n" + largest;
}9) Print Given String is palindrome or notSolution:
import java.io.*;import java.util.*;public class Solution {public static void main(String[] args) {Scanner sc=new Scanner(System.in);String A=sc.next();String reverseString = "";for(int i= A.length()-1; i >=0; i--){reverseString = reverseString + A.charAt(i);}if(reverseString.equals(A)){System.out.println("Yes, String is palindrome");}else{System.out.println("No, String is not palindome");}}}10) Write code to find out two strings are Anagram or not based on insensitivity of strings?Solution: When input string is characters count is exactly same with another string then string is anagram.e.g. Hello - H = 1, e = 1, l = 2, o = 1hello= h = 1, e = 1, l = 2, o = 1In above two strings characters occurrence in both strings are exactly match. We should not consider case sensitivity.so "H" and "h" should not consider different character.package StringExamples;11) Split String using regex, remove all white spaces and special characters.
import java.util.HashMap;
public class StringsAnagram { static boolean isAnagram(String a, String b) {
if(a.length() != b.length()){
return false;
}
HashMap<java.lang.Character, Integer> charCounts =
new HashMap<java.lang.Character, Integer>();
a = a.toLowerCase();
b= b.toLowerCase();
for(int i=0; i< a.length(); i++){
if(charCounts.containsKey(a.charAt(i))){
charCounts.put(a.charAt(i) , charCounts.get(a.charAt(i)) +1);
}else{
charCounts.put(a.charAt(i) , 1);
}
}
HashMap<java.lang.Character, Integer> charCountsB =
new HashMap<java.lang.Character, Integer>();
for(int i=0; i< b.length(); i++){
if(charCountsB.containsKey(b.charAt(i))){
charCountsB.put(b.charAt(i) , charCountsB.get(b.charAt(i)) +1);
}else{
charCountsB.put(b.charAt(i) , 1);
}
}
if(charCounts.equals(charCountsB)){
return true;
}else{
return false;
}
} public static void main(String[] args) {
String a = "Hello";
String b = "hello";
boolean ret = isAnagram(a, b);
System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
}
}Match with given regular expression :[A-Za-z !,?._'@]+, and print the number of tokensSolution:package javaBasics; public class StringSplitRegex {
public static void main(String[] args) {
String str = "He is a very very good boy, isn't he?";
str = str.trim();
String[] tokens;
if(str.isEmpty()) {
tokens = new String[0];
}else {
tokens = str.trim().split("[\\s,?!'']+");
}
System.out.println(str.isEmpty());
System.out.println(tokens.length);
for(int i =0; i< tokens.length; i++){
System.out.println(tokens[i]);
}
} }Test Case 1: He is a very very good boy, isn't he?expected output: 10He is a very very good boy isn t heTest Case 2: (empty string or leading white spaces more than 1)expected output: 0

Comments
Post a Comment