#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Posts
    3
    Rep Power
    0

    Jave string method


    Given a string, if the first or last chars are 'x', return the string without those 'x' chars, and otherwise return the string unchanged.

    withoutX("xHix") → "Hi"
    withoutX("xHi") → "Hi"
    withoutX("Hxix") → "Hxi"
    --------------------------------------------------------------------------------------------
    MY ANSWER
    Code:
    String result = "";
    public String withoutX(String str) { 
    if(str.length()>2){
    if(str.substring(0,1).equals("x") || str.substring(str.length()).equals("x")){
    return str.substring(1,str.length());
    } 
    }
    if(str.length()<=2){
    return result;
    }
    
    return str;
    }
    ----------------------------------------------------------------------------------------
    THIS METHOD IS BEING TESTED WITH THE FOLLOWING :
    expected result your result
    withoutX("xHix") → "Hi" "Hix" X
    withoutX("xHi") → "Hi" "Hi" OK
    withoutX("Hxix") → "Hxi" "Hxix" X
    withoutX("Hi") → "Hi" "" X
    withoutX("xxHi") → "xHi" "xHi" OK
    withoutX("Hix") → "Hi" "Hix" X
    withoutX("xaxbx") → "axb" "axbx" X
    withoutX("xx") → "" "" OK
    withoutX("x") → "" "" OK
    withoutX("") → "" "" OK
    withoutX("Hello") → "Hello" "Hello" OK
    withoutX("Hexllo") → "Hexllo" "Hexllo" OK
    other tests OK
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,714
    Rep Power
    348
    Please explain what problems you are having?

    The code has lost its formatting. Nested statements should be indented.
  4. #3
  5. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,022
    Rep Power
    1285
    Recall that the String is actually composed of an array of characters and arrays are 0 based. Notice the character you check.

IMN logo majestic logo threadwatch logo seochat tools logo