Return a string without the first two characters I'm new to Java and am trying to solve a scenario.  Even though I've succeeded and it works, I've just wondered if there was a more practical way of doing this task.  Is there a quicker or more efficient way of solving the task, or is this fine?


  Task:
  
  Given a string, return a version without the first 2 chars. Except
  keep the first char if it is 'a' and keep the second char if it is
  'b'. The string may be any length. 

deFront("Hello") → "llo"
deFront("java") → "va"
deFront("away") → "aay"



Code:

public String deFront(String str) {    
  if(str.length() &gt; 0) {
    if(str.substring(0,1).equals("a") &amp;&amp; !str.substring(1,2).equals("b")) {
      return str.substring(0,1) + str.substring(2,str.length());
    } else if(str.substring(1,2).equals("b") &amp;&amp; !str.substring(0,1).equals("a")) {
      return str.substring(1,2) + str.substring(2,str.length());
    } else if(str.substring(0,1).equals("a") &amp;&amp; str.substring(1,2).equals("b")) {
      return str;
    } else {
      return str.substring(2,str.length());
    }
  } else {
    return "";
  }
}
Yes, some of the things you are doing is redundant and quite messy. As this seems to be a homework assignment I will only provide hints for you here.

What you can do is:


If the string is empty, return an empty string immediately
Store the first character in a variable
Store the second character in a variable, if it exists
Store the rest of the string in a variable, if it exists
Check if the second character is 'b', if it is then add it to the beginning of the string
Check if the first character is 'a', if it is then add it to the beginning of the string
Return the string


A problem of your existing code is that it will fail for strings of length 1. So it is important to only use the first and second characters if they exist at all.