HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Return a string without the first two characters

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withoutthereturntwofirstcharactersstring

Problem

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() > 0) {
    if(str.substring(0,1).equals("a") && !str.substring(1,2).equals("b")) {
      return str.substring(0,1) + str.substring(2,str.length());
    } else if(str.substring(1,2).equals("b") && !str.substring(0,1).equals("a")) {
      return str.substring(1,2) + str.substring(2,str.length());
    } else if(str.substring(0,1).equals("a") && str.substring(1,2).equals("b")) {
      return str;
    } else {
      return str.substring(2,str.length());
    }
  } else {
    return "";
  }
}

Solution

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.

Context

StackExchange Code Review Q#37055, answer score: 17

Revisions (0)

No revisions yet.