Tuesday, February 22, 2011

JAVA BAT : String 1 : extraEnd

In String 1 section of Java Bat there are basic string problems in which you cannot use loops to solve the problem. We should use string functions like str.length(), str.substring(i,j) etc.

Extra End Problem : Given a string, return a new string made of 3 copies of the last 2 chars of the original string. The string length will be at least 2.
Examples:
extraEnd("Hello") → "lololo"
extraEnd("ab") → "ababab"
extraEnd("Hi") → "HiHiHi"

Solution for this JavaBat extraEnd problem:

public String extraEnd(String str) {

  String lastchars = str.substring(str.length()-2,str.length());
  return lastchars+lastchars+lastchars;

}


Tuesday, February 1, 2011

JAVA BAT : String 1 : Make Out Word

In String 1 section of Java Bat there are basic string problems in which you cannot use loops to solve the problem. We should use string functions like str.length(), str.substring(i,j) etc.

Make Out Word Problem:Given an "out" string length 4, such as "<<>>", and a word, return a new string where the word is in the middle of the out string, e.g. "<>". Note: use str.substring(i, j) to extract the String starting at index i and going up to but not including index j.
Examples:
makeOutWord("<<>>", "Yay") → "<<Yay>>"
makeOutWord("<<>>", "WooHoo") → "<<WooHoo>>"
makeOutWord("[[]]", "word") → "[[word]]"



In this problem we have a method named makeOutWord with two string parameter. The first parameter is a length 4 string and the second string parameter will come in the middle of the first string or in other words left half of the first string will come before the second word and the right half of first string will come after the second word. 

Solution for this JavaBat makeOutWord problem:


    public String makeOutWord(String outside, String inside)
    {

      String left = outside.substring( 0, 2 );
      String right = outside.substring( 2, 4 );
      String str = left + inside + right;
      return str;
    }



This code can also be written in this way:


    public String makeOutWord(String outside, String inside)
    {
      String str = outside.substring( 0, 2 ) + inside 
           + outside.substring( 2, 4 );
      return str;
    }