Java > String-1 > theEnd (CodingBat Solution)

Problem:

Given a string, return a string length 1 from its front, unless front is false, in which case return a string length 1 from its back. The string will be non-empty.

theEnd("Hello", true) → "H"
theEnd("Hello", false) → "o"
theEnd("oh", true) → "o"


Solution:

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


4 comments :

  1. public String theEnd(String str, boolean front) {
    if(front){
    return String.valueOf(str.charAt(0));
    }
    return String.valueOf(str.charAt(str.length() - 1));
    }

    ReplyDelete
  2. public String theEnd(String str, boolean front) {
    if(front){
    return String.valueOf(str.charAt(0));
    }
    return String.valueOf(str.charAt(str.length() - 1));
    }

    ReplyDelete
  3. public String theEnd(String str, boolean front) {
    if(front){
    return String.valueOf(str.charAt(0));
    }
    return String.valueOf(str.charAt(str.length() - 1));
    }

    ReplyDelete
  4. public String theEnd(String str, boolean front) {
    int leng = str.length();
    return (front == true) ? str.substring(0,1) : str.substring(leng-1,leng);
    }

    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