Java Interview Programs - Part 4

1) Reverse a string
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class ReverseString{

 public static void main(String[] args) {
  String str = "Hello World!";
  String rev = "";

  for (int i = str.length() - 1; i >= 0; i--) {
   rev = rev + str.charAt(i);
  }
  System.out.println("Reverse : " + rev);
 }
}
Output: Reverse : !dlroW olleH

Reverse String using recursion
public class TestCls1 {

	public static void main(String[] args) {
		String str = "Hello World!";
String reversed = reverseString(str); System.out.println("The reversed string is: " + reversed); } public static String reverseString(String str) { if (str.isEmpty()) return str;
		return reverseString(str.substring(1)) + str.charAt(0);
	}
}
Output: Reverse : !dlroW olleH

2) Reverse words in string
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class ReverseWords {

 public static void main(String[] args) {
  String str = "Hello World";

  String[] arr = str.split(" ");

  StringBuffer sb = new StringBuffer();

  for (int i = arr.length - 1; i >= 0; i--) {
   sb.append(arr[i]);
   sb.append(" ");
  }
  System.out.println(sb);
 }
}
Output: Reverse words : World Hello

3) Check if given string is palindrome or not
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class Palindrome{

 public static void main(String[] args) {
  String str = "madam";
  String rev = "";

  for (int i = str.length() - 1; i >= 0; i--) {
   rev = rev + str.charAt(i);
  }
  if (str.equals(rev))
   System.out.println("Palindrome");
  else
   System.out.println("Not Palindrome");
 }
}
Output: Palindrome

4) Replace all the spaces in string with Test.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class ReplaceSpaceWithTest{

 public static void main(String[] args) {
  String str = "World is beautiful";
  StringBuffer sb = new StringBuffer();
  
  for(int i = 0; i<str.length(); i++) {
   if (str.charAt(i) == ' ') {
    sb.append("Test");
   }else {
    sb.append(str.charAt(i));
   }
  }
  System.out.println(sb);
 }
}
Output: WorldTestisTestbeautiful

5) Remove all the white-spaces in string.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class RemoveAllWhiteSpaces{

 public static void main(String[] args) {
  String str = "World Is Beautiful";
  StringBuffer sb = new StringBuffer();
  
  for(int i = 0; i<str.length(); i++) {
   if (!(str.charAt(i) == ' ')) {
    sb.append(str.charAt(i));
   }
  }
  System.out.println(sb);
 }
}

6) Replace particular character in given String
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class ReplaceCharInString{

 public static void main(String[] args) {
  String str = new String("World Is Beautiful!!");
  String newStr = "";
  
  for(int i = 0; i<str.length(); i++) {
   if(str.charAt(i) == '!') {
    newStr=newStr + '?';
   }else {
    newStr=newStr + str.charAt(i);
   }
  }
  System.out.println(newStr);
 }
}

7) Replace a substring inside a string by another one ?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class ReplaceString{

 public static void main(String[] args) {
  String str = new String("This is a demo string");
  StringBuffer sb = new StringBuffer();
  String searchChar ="demo";
  String replaceWith="sample";
  
  String[] stringArray = str.split(" ");
  
  //Replace demo with sample
  for(int i = 0; i<stringArray.length; i++) {
   if(stringArray[i].equals(searchChar)) {
    sb.append(replaceWith);
   }else {
    sb.append(stringArray[i]);
   }
   sb.append(" ");
  }
  System.out.println(sb);
 } 
}
Output: This is a sample string
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class ReplaceImplementation {
	public static void main(String[] args) {
		String str = "This is a demo example of demo string";
		String searchChar = "demo";
		String replaceWith = "sample";
		System.out.println(demoFunction(searchChar, replaceWith, str));
		System.out.println(demoFunction1(searchChar, replaceWith, str));
	}

	// Replace All Matching Words
	public static String demoFunction1(String oldWorld, String newWord, String input) {

		int i = input.indexOf(oldWorld);

		if (i < 0) {
			return input;
		}

		String partBefore = input.substring(0, i);
		String partAfter = input.substring(i + oldWorld.length());

		return partBefore + newWord + demoFunction1(oldWorld, newWord, partAfter);
	}
}

8) How to search a word inside a string ?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class SearchSubString {
    public static void main(String[] args) {
        String str = "Book - Learn Java by Examples";
        String lookUpString = "Java";

        // Checks to see if the word "Java" is found in the str
        if (str.indexOf(lookUpString) != -1) {
            System.out.println("Found the word " + lookUpString + " at index number " + str.indexOf(lookUpString));
        } else {
            System.out.println("Can't find " + lookUpString);
        }

        // Or using String.contains() method
        if (str.contains(lookUpString)) {
            System.out.println("Found the word " + lookUpString);
        }
    }
}
Output: 
Found the word Java at index number 13
Found the word Java

9) Find out maximum repeating character in a string?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.string;

import com.array.Test;

public class FindMaxOccuringChar {
 static final int ASCII_SIZE = 256;

 static char getMaxOccuringChar(String str) {
  // Create array to keep the count of individual
  // characters and initialize the array as 0
  int count[] = new int[ASCII_SIZE];

  // Construct character count array from the input
  // string.
  int len = str.length();
  for (int i = 0; i < len; i++)
   count[str.charAt(i)]++;

  int max = -1; // Initialize max count
  char result = ' '; // Initialize result

  // Traversing through the string and maintaining
  // the count of each character
  for (int i = 0; i < len; i++) {
   if (max < count[str.charAt(i)]) {
    max = count[str.charAt(i)];
    result = str.charAt(i);
   }
  }
  return result;
 }

 public static void main(String[] args) {
  FindMaxOccuringChar maxOccuringChar = new FindMaxOccuringChar();
  System.out.println(maxOccuringChar.getMaxOccuringChar("ccaaabbr"));
 }
}
Output: a

10) Count the number of occurrences of each character in a string
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Test {
 public static void main(String[] args) {

  String str = "bcdebcaaa";
  HashMap<Character, Integer> map = new HashMap<>();
  int maxCount = 0;
  Character maxChar = ' ';

  for (int i = 0; i < str.length(); i++) {
   Character currentChar = str.charAt(i);

   if (map.containsKey(currentChar)) {
    map.put(currentChar, map.get(currentChar) + 1);
   } else {
    map.put(currentChar, 1);
   }

   /*
     if(map.get(currentChar)>maxCount) { 
                                 maxCount = map.get(currentChar); 
                                 maxChar  = currentChar; 
                               }
    */
  }
  System.out.println(map);
 }
}

11) find the duplicate words and their number of occurrences in a string?
12) Sorting the String without using String API
13) check if two Strings are Anagrams
14) Reverse order of words in a String

<-- Previous || Next -->

No comments:

Post a Comment