• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

What is this line doing?

 
Ranch Hand
Posts: 289
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
in this method exercise

what is this line doing?



I understand that substring is creating another string from an existing string (in this case str)
but position, position + length

position, depending on the length of the string is either 1 or 2 (1 for odd, 2 for even)
i get that, but how is is picking the middle of the string from position to position + length?



 
Rancher
Posts: 4801
50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As the code comment says, if the string is an even length then the middle of the String is two characters:
123456
The middle would be 34.

For an odd length the middle is a single character:
1234567 gives 4.

So the if statement has determined whether the String is even or odd, and set the value of position to the first character of the 'middle', and the length of the middle.
So position of 123456 would be 2, which represents the number 3 in the String as positions are 0-based, with a length of 2.

For 1234567 you would have a position of 3 (it's int division, so the 0.5 is lost), which is the position of the 4, with a length of 1.
 
wayne brandon
Ranch Hand
Posts: 289
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
right Dave, I wrote those comments and just needed to check if i was right, thanks!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic