Given a string, return a a string with either the middle character removed, when the original string contains an odd number of characters, or the middle two characters removed when the original string contains an even number of characters. Assume there will be at least one character in the original string. Note that you can do this without an if statement.
this works for a word that has an odd length but how can i make it so it can also remove the 2 middle characters if the word length is even??
how can i make it so it can also remove the 2 middle characters if the word length is even??
First detect an even length.
Have you tried with paper and pencil to get the indexes and lengths for the parts of the String that need to be extracted and put together again to build a new String with the middle 2 characters removed?
|length of string||start of left||end of left||start of right||end of right|
Fill in the rest of the table and see if you recognize a pattern.
If I were doing this, I would use a StringBuilder object.
Stephan van Hulst wrote:You don't need a modulo operator. In fact, you don't need to determine at all whether the length is even or odd.
Ok, I see how you can solve this without using the remainder operator.
Piet Souris wrote:You do not need to determine the length.
Not sure what you mean by that because length() is central to the solution, at least it is with the one I got. Are you saying you don't need length() at all or did you mean to say that you don't need to determine whether the length is odd or even?
L Hasan wrote:Do you think in this instance, the ternary operator counts as an 'if'? ;)
Yes, it counts as an if
It's a bit of a brain-teaser, I must admit.
Hint: First cut off the right side to the correct length, then you can use that piece to measure how much of the left side you need to take.
All i have is this and this only works for any word that has an even amount of characters. i do apologize i am new to this site and barely learning java. i appreciate all the tips and help.
Junilu Lacar wrote:Assuming the method you write is named noMid(), here's some code you can use to test your implementation:
This might be a good, albeit in-depth, opportunity to read up on Test-Driven Development (TDD). This way of testing the implementation fits perfectly into that.
Alvaroo, write down on a piece of paper:
Write indices above each character. Write strings lengths on the right of each string. Once you workout right hand side string start and end indices, think how you can calculate left hand side string start and end.
All is simpler thank you might think. Just visualise all exercise on a paper.