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

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact