Java > String-1 > without2 (CodingBat Solution)

Problem:

Given a string, if a length 2 substring appears at both its beginning and end, return a string without the substring at the beginning, so "HelloHe" yields "lloHe". The substring may overlap with itself, so "Hi" yields "". Otherwise, return the original string unchanged.

without2("HelloHe") → "lloHe"
without2("HelloHi") → "HelloHi"
without2("Hi") → ""


Solution:

public String without2(String str) {
  int len = str.length();
  if (len == 2)
    return "";
  if (len < 2)
    return str;
  else {
    if (str.substring(0,2).equals(str.substring(len-2, len)))
      return str.substring(2,len);
      else return str;
  
  } 
}


5 comments :

  1. public String without2(String str) {

    if(str.length()>1 && str.substring(0,2).equals(str.substring(str.length()-2)))
    return str.substring(2,str.length());
    else return str;
    }

    ReplyDelete
    Replies
    1. this one actually worked for me, the suggested solution in the main post didn't :) thanks!

      Delete
  2. public String without2(String str) {
    int x = str.length();

    if(x == 1)
    {
    return str;
    }
    else if(x <= 2)
    {
    return "";
    }
    else if(str.substring(0,2).equals(str.substring(x-2,x)))
    {
    return str.substring(2,x);
    }
    else
    {
    return str;
    }
    }

    ReplyDelete
  3. public String without2(String str) {
    if(str.length() >= 2) {
    String front = str.substring(0, 2), back = str.substring(str.length() - 2);
    if(front.equals(back)) return str.substring(2);
    }
    return str;
    }

    ReplyDelete
  4. public String without2(String str) {
    return str.length() > 1 && str.substring(0,2).equals(str.substring(str.length()-2)) ? str.substring(2, str.length()):str;

    }

    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