Showing posts with label String. Show all posts
Showing posts with label String. Show all posts

Java program to find palindromic substring in a string.



public class PalidrumSubString 
{
 public static void main(String args[]) 
 {
  String s = "my name rar kumar poop";
  String p[] = s.split(" ");
  String s2 = "";
  for (int j = 0; j < p.length; j++) 
  {
   for (int i = p[j].length() - 1; i >= 0; i--) 
   {
    char z = p[j].charAt(i);
    s2 = s2 + z;
   }

   if (p[j].equals(s2)) 
   {
    System.out.println(s2);
   }
   else 
   {
    s2 = "";
   }
  }
 }
}

Output:
rar
poop


Java program to find the frequency of one string in another string.



import java.util.Scanner;
public class WordFrequencyCounter {
    public static void main(String args[]) {
        Scanner scan = new Scanner(System.in);
        System.out.println("enter main string");
        String s = scan.nextLine();
        System.out.println("enter string to be searched");
        String f = scan.nextLine();
        s = s + " ";
        int l = s.length();
        char a;
        int c = 0;
        String s1 = "";
        for (int i = 0; i < l; i++) {
            a = s.charAt(i);
            if (a != ' ') {
                s1 = s1 + a;
            } else {
                if (s1.equalsIgnoreCase(f) == true) {
                    c++;
                }
                s1 = "";
            }
        }
        System.out.println("Frequency of the word " + f + " is " + c);
    }                                         
}

Output:
Enter main string
Umesh Kumar Kushwaha Kumar
enter string to be searched
Kumar
Frequency of the word Kumar is 2



Java program to remove vowels from a string.



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RemoveVowels
{
 public static void main(String args[]) throws IOException {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   String str1, str2 = "";
   char ch, ch1;
   int i, len;
   System.out.println("Enter the Sentence:");
   str1 = br.readLine();
   len = str1.length();
   for (i = 0; i < len; i++) {
    ch = str1.charAt(i);
    ch1 = Character.toLowerCase(ch);
    switch (ch1) {
     case 'a':
     case 'e':
     case 'i':
     case 'o':
     case 'u':
      break;
     default:
      str2 = str2 + ch;
    }                           //switch ends
   }                            //for ends
   System.out.println("Modified string without vowels:" + str2);
  }                            //method ends
}

Output:
Enter the Sentence:
umesh kumar kushwaha
Modified string without vowels:msh kmr kshwh


Java program to remove common characters from two strings.



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class RemoveCommonDuplicateChar 
{
 public static void main(String args[]) throws IOException {
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String s1, s2, s3 = "", s4 = "";
  int a[], b[], x = 0, y = 0;
  int len1, len2;
  char ch;
  int i, j;
  System.out.println("Enter the first sentence:");
  s1 = br.readLine().trim();
  System.out.println("Enter the second sentence:");
  s2 = br.readLine().trim();
  len1 = s1.length();
  len2 = s2.length();
  a = new int[len1];
  b = new int[len2];
  for (i = 0; i < len1; i++) {
   ch = s1.charAt(i);
   for (j = 0; j < len2; j++) {
    if (ch == s2.charAt(j)) {
     break;
    }
   }
   if (j != len2) {
    a[x++] = i;
    b[y++] = j;
   }
  }
  for (i = 0; i < len1; i++) {
   for (j = 0; j < x; j++) {
    if (i == a[j]) {
     break;
    }
   }
   if (j == x) {
    s3 = s3 + s1.charAt(i);
   }
  }
  for (i = 0; i < len2; i++) {
   for (j = 0; j < y; j++) {
    if (i == b[j]) {
     break;
    }
   }
   if (j == y) {
    s4 = s4 + s2.charAt(i);
   }
  }
  System.out.println("Original string1=" + s1 + " Modified string1=" + s3);
  System.out.println("Original string2=" + s2 + " Modified string2=" + s4);
 }
}

Output:

Enter the first sentence:
Umesh Kumar Kushwaha
Enter the second sentence:
Rahul Kumar Singh
Original string1=Umesh Kumar Kushwaha Modified string1=Uessw
Original string2=Rahul Kumar Singh Modified string2=Rlua Singh


Java program to reverse a String without using direct method.



import java.io.BufferedReader;
public class ReverseOfString {
 public static String reverseString(String s)
 {
  int l = s.length();
  String backward = "";
  for (int i = l - 1; i >= 0; i--) 
 {
   backward = backward + s.charAt(i);
  }
  return backward;
 }
 public static void main(String args[]) {
  String backwards = reverseString("Umesh Kushwaha");
  System.out.println("Reverse String is " + backwards);
 }
}


Output:
Reverse String is ahawhsuK hsemU



Java program to finding Shortest and Longest Words in a String.



import java.io.BufferedReader;
class FindMinMaxString {
 public static void main(String args[]) {
  findMethod("My name is Umesh Kushwaha");
 }
 static public void findMethod(String s) {
  String str = s + " ";
  char ch = ' ';
  int len = str.length(), l = 0;
  int min = len, max = 0;
  String shortest_word = "", longest_word = "", word = "";
  for (int i = 0; i < len; i++) {
   ch = str.charAt(i);
   if (ch != ' ') {
    word += ch;
   }                                     //if ends
   else {
    l = word.length();
    if (l < min) {
     min = l;
     shortest_word = word;
    }                                     //if ends
    if (l > max) {
     max = l;
     longest_word = word;
    }
    word = "";
   }
  }
  System.out.println("Shortest word = " + shortest_word + " with length " + min);
  System.out.println("Longest word = " + longest_word + " with length " + max);
 }
}

Output:
Shortest word = My with length 2
Longest word = Kushwaha with length 8



Java program to input name, middle name and surname of a person and print only the initials.



Example.

Enter your name
Umesh Kumar Kushwaha
Initials are   U.K.K.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class InitialName {
 public static void main(String args[]) throws IOException {
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter your name");
  String s = br.readLine(), s1 = "";
  s = " " + s;
  int len = s.length();
  char a;
  for (int i = 0; i < len; i++) {
   a = s.charAt(i);
   if (a == ' ') {
    s1 = s1 + s.charAt(i + 1) + ".";
   }
  }
  System.out.println("Initials are   " + s1);
 }
}

Output:
Enter your name
Umesh Kumar Kushwaha
Initials are   U.K.K.



Java program to accept a string and print each character of the string along with its ASCII code.



class CalculateAscii {
 public static void main(String args[]) {
  word("Umesh Kushwaha");
 }
 static void word(String s) {
  int len = s.length();
  int a;
  char a1;
  for (int i = 0; i < len; i++) {
   a1 = s.charAt(i);
   a = a1;
   System.out.println(a1 + "–>" + a);
  }
 }
}


Output:

U–>85
m–>109
e–>101
s–>115
h–>104
 –>32
K–>75
u–>117
s–>115
h–>104
w–>119
a–>97
h–>104
a–>97


Java program to count the occurrence of any character in given String.



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

class CountFrequencyOfWord {
 public static void main(String args[]) {
  try {
   input();
  } catch (IOException ex) {
   Logger.getLogger(CountFrequencyOfWord .class.getName()).log(Level.SEVERE, null, ex);
  }
 }
 static void input() throws IOException {
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter a sentence");
  String s = br.readLine();
  System.out.println("Enter the letter ");
  char a = (char) br.read();
  int len = s.length();
  int c = 0;
  char x;
  for (int i = 0; i < len; i++) {
   x = Character.toLowerCase(s.charAt(i));
   if (x == a)
    c = c + 1;
  }
  System.out.println("Frequency of the letter  " + a + " in the sentence " + s + " is " + c);
 }
}



Output:

Enter a sentence
Hi my name is umesh
Enter the letter 
m
Frequency of the letter  m in the sentence "Hi my name is umesh" is 3


Java program to remove duplicates characters from given String.



class RemoveDuplicate {
 public static void main(String args[]) {
  remove("123aa bbbcc  c2589  99oppq rtyyy");
 }
 static void remove(String s) {
  int l = s.length();
  int c;
  String org = s, s1 = "";
  for (int i = 0; i < (l - 1); i++) {
   s1 = s.substring(0, i + 1);
   c = 0;
   for (int j = i + 1; j < l; j++) {
    if (s.charAt(i) == s.charAt(j)) {
     c++;
     continue;
    } else
     s1 = s1 + s.charAt(j);
   }
   s = s1;
   s1 = "";
   if (c > 0)
    l -= c;
  }
  System.out.println("Original String:" + org);
  System.out.println("String after removing duplicates:  " + s);
 }
}


Output:

Original String:123aa bbbcc  c2589  99oppq rtyyy

String after removing duplicates:  123a bc589opqrty


String based interview Questions



1. What would you use to compare two String variables - the operator == or the equals() method?
I would personally prefer/use the equals() method to compare two Strings if I want to check the value of the Strings and the == operator if I want to check if the two variables point to the same instance of the String object.



2. For concatenation of strings, which class is good, StringBuffer or String ? 
StringBuffer is faster than String for concatenation. Also, it is less memory/resource intensive when compared to Strings.



3. As a continuation to the previous question - Why would you say StringBuffers are less resource intensive than Strings during Concatenation? 
As you might already know, Strings are immutable. So, when you concatenate some value to a String, you are actually creating a fresh String object that is going to hold some more data. This way you have created a new object while the old String object is still alive. As you keep concatenating values to the String, newer objects are going to get created which are going to use up the virtual memory. Whereas, if you use a StringBuffer, you are just editing the objects value rather than creating new objects.



4. To what value is a variable of the String type automatically initialized?
 The default value of String variable is null.



5. What is the difference between the String and StringBuffer classes?
String objects are constants or in other words immutable while StringBuffer objects are not.



6. What happens when you add a double value to a String? 
The result is a String object. For that matter, if you add anything to a String, you will end up with a String.



7. What will be the result if you compare StringBuffer with String if both have same values?
It will return false as you cannot compare String with StringBuffer directly. If you really want to compare the contents of the String & the StringBuffer you would have to invoke the equals method with the String and the toString() output of the StringBuffer.



8. What is difference between String, StringBuffer and StringBuilder? When to use them?
For all practical understanding purposes, all these 3 classes are used to handle/manipulate Strings. The main difference between these 3 classes is:

* Strings are immutable while StringBuffer & StringBuilder objects are mutable (can be modified)
* StringBuffer is synchronized (thread safe) while StringBuilder is not.



9. When to use Strings or StringBuffer or StringBuilder? What will drive this decision? 
The type of objects you need to create and how they will be used will drive this decision. So,

* If the object value is not going to change, use the String class
* If the object value will be changed frequently we must choose either the StringBuffer or the StringBuilder.
* Here, if your object will be accessed only by a single thread use StringBuilder because it is faster
* If your object may be accessed my multiple threads use the StringBuffer because it is thread safe

Note: Thread safety is not free and comes at the expense of performance. So, if your system is not multi-threaded then use the StringBuilder which will be much faster than the StringBuffer.



10. Why String class is final or immutable?
The reason "Why" the string class is final is because - The developers of the Java language did not want programmers to mess with the basic functionality of the String Class. Almost all the basic or core functionality related classes in Java are final for the same reason.

If String were not final, you could create a subclass and have two strings that look alike when you see the value in the string, but that are actually different.

Ex: See the two string objects below, MyString and YourString are two classes that are sub-classes of the "String" class and contain the same value but their equality check might fail which does not look right. Doesnt it?

MyString str1 = "Rocky";
YourString str2 = "Rocky";

This is why String class is final. 


How to reverse a String without using any direct method.



public class ReverseOfString 
{
    public static void main(String args[])
    {
        String s = "UMESH KUMAR";
        char a[] = new char[s.length()];
        int n = s.length() - 1;
        for (int i = 0; i < s.length(); i++) 
        {
            a[i] = s.charAt(n);
            n--;
        }
        String rev = new String(a);
        System.out.println(rev);
    }
}


Output:  RAMUK HSEMU