Java > String-1 > firstHalf (CodingBat Solution)

Problem:

Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".

firstHalf("WooHoo") → "Woo"
firstHalf("HelloThere") → "Hello"
firstHalf("abcdef") → "abc"


Solution:

public String firstHalf(String str) {
  int half = str.length() / 2;
  return str.substring(0, half);
  
}

3 comments:

  1. public String firstHalf(String word) {
    return word.substring(0, word.length() / 2);
    }

    ReplyDelete
  2. public String firstHalf(String str) {
    int s1 =str.length(), half =s1/2;
    return str.substring(0,half);
    }

    ReplyDelete
  3. tried all codes and they failed, the correct code is this following:

    public String theEnd(String str, boolean front) {
    int len = str.length();
    String s1 = new String();
    if(front){
    s1 = str.substring(0,1);}
    else{
    s1 = str.substring(len-1);
    }
    return s1;
    }

    ReplyDelete