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);
     }

}

3 comments:

  1. Hey, thanks for the solution but sorry to say this, but it didn't work! You're wrong, dude

    ReplyDelete
  2. don't know why it wasn't working. I copied it and everything, but it still didn't work!

    ReplyDelete