Friday, March 11, 2011

JAVA BAT : String 1 : firstTwo

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.

First Two Problem: Given a string, return the string made of its first two chars, so the String "Hello" yields "He". If the string is shorter than length 2, return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "". Note that str.length() returns the length of a string.
Examples:
firstTwo("Hello") → "He"
firstTwo("abcdefg") → "ab"
firstTwo("ab") → "ab"

Solution for this JavaBat firstTwo problem:


public String firstTwo(String str) {          

     if(str.length()<2){
         return str;
     }
     else{
         return str.substring(0,2);
     }

}

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;

}