How camelCase String in Pharo?

I am trying to get from:

'hello how are you today' 

to

 'helloHowAreYouToday' 

And I thought that asCapitalizedPhrase asLegalSelector would do the trick, but that is not the case.

What is the right way to do this?

EDIT:

I think I should clarify my question; I already have a way to turn a string into a camelCase selector:

 |aString aCamelCaseString| aString := aString findTokens: $ . aCamelCaseString := aString first. aString allButFirst do: [:each | aCamelCaseString := aCamelCaseString , each capitalized]. 

I'm just wondering if Pharo has a standard system method to achieve the same :)

+4
source share
4 answers

You don’t say which version of Pharo you are using, but in stable 5.0,

 'hello world this is a selector' asCamelCase asValidSelector 

gives

 helloWorldThisIsASelector 

To get what I use run:

 curl get.pharo.org/50+vm | bash 
+1
source

How about this?

 | tokens | tokens := 'this is a selector' findTokens: Character space. tokens allButFirst inject: tokens first into: [:selector :token | selector, token capitalized] 
+8
source

I do not think there is an existing method.

Here's an implementation that solves your problem:

 input := 'hello how are you today'. output := String streamContents: [ :stream | | capitalize | capitalize := false. input do: [ :char | char = Character space ifTrue: [ capitalize := true ] ifFalse: [ stream nextPut: (capitalize ifTrue: [ char asUppercase ] ifFalse: [ char ]). capitalize := false ] ] ]. 

Edit: notice that compared to Frank's decision, it is longer, but it does not interrupt for empty input and does not create a new line instance for each step, since it passes streams through the input, which is more efficient (if you have large lines).

+3
source

I know this is old, but Squeak has a useful implementation (String -> asCamelCase) that basically does this:

 (String streamContents: [:stream | 'hello world' substrings do: [:sub | stream nextPutAll: sub capitalized]]) asLegalSelector 
0
source

Source: https://habr.com/ru/post/1340963/


All Articles