Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract a substring from a string in smalltalk (squeak)

I'm trying to extract a substring from a string which would be the substring in between 2 delimiters i.e it should be defined as follows:

substring: aString delimiter: aDelimiter

and, for an example, if i'll get this line:

substring: 'dddd#sss#dddd' delimiter: '#'

the function should return 'sss'.

this is what i've been trying, which didn't work:

substring: aString delimiter: aDelimiter
|index temp1 temp2 sz arr str|
      arr := aString asArray.
      sz := arr size.
      index := arr lastIndexOf: aDelimiter.
      temp1 := arr first: (sz - index +1).
      index := temp1 lastIndexOf: aDelimiter.
      sz :=temp1 size.
      temp2 := temp1 first: (sz - index).
      str := temp2 asString.
      ^str.

I don't know if it's worth mentioning but it's supposed to be a class method.

like image 565
Just Me Avatar asked Jan 10 '23 07:01

Just Me


2 Answers

Your basic problem is that the argument aDelimiter is a string instead of a character. You want to call it with $# instead of '#'.

Now for some easier ways. Probably the easiest is to use the subStrings: method:

('dddd#sss#dddd' subStrings: '#') at: 2

This has the disadvantage that it extracts the entire string into substrings separated by the # character which may be more than you need.

The next easiest option is to use streams:

'dddd#sss#dddd' readStream upTo: $#; upTo: $#

That code only extracts the part that you need.

like image 111
David Buck Avatar answered Jan 27 '23 23:01

David Buck


You aren't far from working code, as David pointed out. But I'd just like to point out that it's very procedural. A lot of the magic of Smalltalk, and OOP in general, is writing beautiful, easy to understand code that sends intention revealing messages to a community of appropriate objects. This includes leaning on the objects already existing in the image. I can't think of a time when I've had to go this low level for a simple task like this. It would be great to read one of the many awesome OOP references. My favorite is A Mentoring Course on Smallalk

I think David's solution is right on. I personally like second instead of at: 2, but it feels picky and might be personal preference ('dddd#sss#dddd' subStrings: '#') second

like image 25
Sean DeNigris Avatar answered Jan 27 '23 23:01

Sean DeNigris