Friday 10 January 2014

Java : Change case of the entered string from uppercase to lowercase

public class Ques2 {
/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    //ascii A=65 Z=90 a=97
    System.out.println("Enter UPPERCASE");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   // String input = br.readLine().toLowerCase();
    char c;
    char[] word=br.readLine().toCharArray();
   for(int i :word)
   {
       if(i>=65 && i<=90){
       i=i+32 ;
       c=(char) i;
        System.out.println(c);
       }
       else{
           c=(char)i;
           System.out.println(c);
       }
   }

}
}

Java: String Compression - How to compress string in the given format

Write a routine that takes as input a string such as "aabbccdef" and outputs "a2b2c2def" or "a4bd2g4" for "aaaabddgggg". Write a ship quality code.


import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

/**
 *
 * @author Sunshine
 */
public class Ques2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = br.readLine().toLowerCase();
       StringBuilder result = new StringBuilder();
        char currentCharacter;
        int count;

        for(int i = 0; i < input.length(); i++) {
            currentCharacter = input.charAt(i);
            count = 1;
            while(i < input.length() - 1 && input.charAt(i + 1) == currentCharacter) {
                count++;
                i++;
            }
            result.append(currentCharacter);
            result.append(count);
        }

        System.out.println(""+result);
    }
}

Thursday 9 January 2014

Java : Program to print all permutations of a given string.

A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
Below are the permutations of string ABC. ABC, ACB, BAC, BCA, CAB, CBA

public class Ques2 {

    /**
     * @param args the command line arguments
     */
   public static void permutation(String str) { 
    permutation("", str); 
}

private static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0) System.out.println(prefix);
    else {
        for (int i = 0; i < n; i++)
            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
    }
}

        
    public static void main(String[] args) throws IOException {

       String str="abc";
       permutation(str);
}
}

Java:Find position of a string in another string.

Find position of a string in another string. For example your first string is 'careerstack' and the second string is 'stack' then the output should be 7.


public class Ques2 {

    /**
     * @param args the command line arguments
     */
   
        
    public static void main(String[] args) throws IOException {

       String match = "kiran";
        String text = "kiranhellooooookiran";
        int i =0;
        while((i=(text.indexOf(match,i)+1))>0)
            System.out.println(i-1);         
        }  

}

Java:Find the number of times each character occurs in the string.

Calculate the frequency of each character in a given string
eg teddy d= 2 e=1 t=1 y=1

import java.io.IOException;

/**
 *
 * @author Sunshine
 */
public class Ques2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {

        String str = "hello kiran";
        int count = 0;
        String temp = "";
        for (int i = 0; i < str.length(); i++) {

            char c = str.charAt(i);  // take one character (c) in string

            for (int j = i; j < str.length(); j++) {

                char k = str.charAt(j);
                // take one character (c) and compare with each character (k) in the string
                // also check that character (c) is not already counted.
                // if condition passes then increment the count.
                if (c == k && temp.indexOf(c) == -1) {
                    count = count + 1;
                }
            }

            if (temp.indexOf(c) == -1) // if it is not already counted
            {
                temp = temp + c; // append the character to the temp indicating
                // that you have already counted it.

                System.out.println("Character   " + c + "   occurs   " + count + "    times");
            }
            // reset the counter for next iteration 
            count = 0;

        }


    }
}

Java: find if two words are anagram in an array of strings




/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ques2;

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

/**
 *
 * @author Sunshine
 */
public class Ques2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        String AS[] = new String[]{"", "", "", "", "", ""};
        System.out.println("Enter array of strings");
        for (int i = 0; i < AS.length; i++) {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            AS[i] = br.readLine().toLowerCase();
        }
        for (int i = 0; i < AS.length; i++) {
            for (int j = i + 1; j < AS.length; j++) {
                if (AS[i].length() == AS[j].length()) {
                    char c1[] = null;
                    char c2[] = null;
                    c1 = AS[i].toCharArray();
                    c2 = AS[j].toCharArray();

                    Arrays.sort(c1);
                    Arrays.sort(c2);

                    if (Arrays.equals(c1, c2)) {
                        System.out.println("Both strings are equal and hence they have anagram at " +i+j);
                    } else {
                        System.out.println("Sorry No anagram in the strings entered");
                    }
                }
            }
        }



    }
}

Wednesday 8 January 2014

Java: finding if two words are anagrams of each other

The steps are:
  1. check the length of of both the words/strings if they are equal then only proceed to check for anagram else do nothing
  2. sort both the words/strings and then compare
package anagram;

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

/**
 *
 * @author Sunshine
 */
public class Anagram {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        System.out.println("Enter the first string");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s1 = br.readLine().toLowerCase();
        System.out.println("Enter the Second string");
        BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
        String s2 = br2.readLine().toLowerCase();
        char c1[] = null;
        char c2[] = null;
        if (s1.length() == s2.length()) {


            c1 = s1.toCharArray();
            c2 = s2.toCharArray();

            Arrays.sort(c1);
            Arrays.sort(c2);

            if (Arrays.equals(c1, c2)) {
                System.out.println("Both strings are equal and hence they have anagram");
            } else {
                System.out.println("Sorry No anagram in the strings entred");
            }

        } else {
            System.out.println("Sorry the string do not have anagram");

Java: Remove duplicate elements in a string

Given a string *Str of ASCII characters, write the pseudo code to remove the duplicate elements present in them. For example, if the given string is "Potato", then, the output has to be "Pota". Additional constraint is, the algorithm has to be in-place( no extra data structures allowed).



public class HelloWorld{

     public static void main(String []args){
         String str="potato";
        int[] A = new int[256];//maximum value of an ASCII character
        StringBuffer sb = new StringBuffer();

        int len = str.length();
        for (int i = 0; i < len; i++)
        {
            char c = str.charAt(i);
            if (A[c] == 0)
            {
                A[c] = 1;
                sb.append(c);
            }
        }

    sb.toString();
            
    System.out.println(""+sb);
     }
}

Java: Replace given pattern with 'X'

Replace all occurrence of the given pattern to 'X'.For example, given that the pattern = 'abc', replace 'abcdeffdfegabcabc' with 'XdeffdfegX'. Note that multiple occurrences of abc's that are contiguous will be replaced with only one 'X'.

public class HelloWorld{

     public static void main(String []args){
         String s1="Helloabckiranabchowareabcyou";
    s1=s1.trim().replaceAll("abc", "X");
    System.out.println(""+s1);
     }

}

Java: Write a program to compact spaces in a string

Write a program to compact spaces in a string i.e. Given a string you have to remove multiple occurrences of blank spaces by a single space and do that in a single pass of the arrays

public class HelloWorld{

     public static void main(String []args){
         String s1="Hello    kiran   how are   you";
    s1=s1.trim().replaceAll("\\s+", " ");
    System.out.println(""+s1);
     }

}