Java > String-1 > withouEnd2 (CodingBat Solution)

Problem:

Given a string, return a version without both the first and last char of the string. The string may be any length, including 0.

withouEnd2("Hello") → "ell"
withouEnd2("abc") → "b"
withouEnd2("ab") → ""

Solution:

public String withouEnd2(String str) {
int len = str.length();
if (len < 3)
return "";
else
return str.substring(1,str.length()-1);
}


7 comments :

  1. public String withouEnd2(String str) {
    if(str.length()==1)
    return str = "";
    if(str.length()>1)
    str = str.substring(1,str.length()-1);
    return str;
    }

    ReplyDelete
  2. public String withouEnd2(String str) {


    if(str.length() <= 1){
    return "";
    }

    else{
    String mid = str.substring(1,str.length() -1);
    return mid;
    }
    }

    ReplyDelete
  3. public String withouEnd2(String str) {
    return (str.length() <= 2)? "" : str.substring(1, str.length() - 1);
    }

    ReplyDelete
  4. if (str.length()>2)
    return str.substring(1,str.length()-1);

    else
    return "";

    ReplyDelete
  5. if(str.length() > 2) {
    return str.substring(1, str.length()-1);
    } else
    return "";

    ReplyDelete
  6. alternative solution :


    public String withouEnd2(String str) {
    String s1 = str , s2 = "";
    int len = s1.length();
    if(len <3){
    s2= "";
    }else{
    s2= s1.substring(1,len-1);
    }
    return s2;
    }

    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