Talking a slice of a string in Pharo smalltalk
Asked Answered
A

1

6

I have a string an I would like to be able to take a substring from the middle of it. For example for the string 'abcdefg' I want to get 'cde' (but the exact start and stop could be arbitrary). I have found allButFirst: and allButLast: messages so I can do it in two steps like

str := 'abcdefg'
(str allButFirst: 2) allButLast: 2

But I was expecting there to be a single message. I also tried using from:to: (which naively makes sense to me) but that doesn't work on the string class.

Is there a message in Pharo 9 Smalltalk that will take the start and stop or start and length for getting a substring?

Alleviation answered 10/7, 2021 at 4:58 Comment(0)
T
10

You can use

'abcdefg' copyFrom: 3 to: 5

and get cde.

Here is one more important piece of advice:

You can go to Main Menu -> Tool -> Finder. Then in the Finder window switch from selectors search to examples. Then in the search bar enter

'abcdefg' . 3 . 5 . 'cde'

These are the "4 elements" of the search. The first one is the receiver, the last one is the expected result, and the middle elements will be used as parameters. So if there is any method that does what you expect, you will see in among the results.

Timms answered 10/7, 2021 at 5:36 Comment(1)
That is a really great tip about the search, had no idea that you can search examples!Alleviation

© 2022 - 2024 — McMap. All rights reserved.