Блог пользователя mayukh03

Автор mayukh03, история, 20 месяцев назад, По-английски

I have trouble finding the indexes or lengths of subsegments of arrays/strings.

For eg. If I want to extract the last k characters of a string s of length n(n>=k), the most normal way to do it is s.substr(n-k,k). But it takes me a few more seconds than it normally should, as I get confused whether the 'n-k' actually takes me to kth character from the end or a character before/after it.

Why do I face this issue and how do I get rid of it?

  • Проголосовать: нравится
  • -17
  • Проголосовать: не нравится

»
20 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

I struggle with this issue too. So I am looking for better ways about thinking about this too.

One thing that might help is between 1, k there are k numbers. 0-indexing means the kth character is at index k-1.

Now the same process can be applied backwards. Starting from the back, n-0, n-1, ..., n-k is a total of k+1 numbers. Hence the kth number from the back is n-k+1. With 0 indexing this is n-k.