简体   繁体   中英

How to camelCase a String in Pharo?

I'm trying to get from:

'hello how are you today'

to

'helloHowAreYouToday'

And I thought asCapitalizedPhrase asLegalSelector would do the trick, but it doesn't.

What's the proper way to do this?

EDIT:

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

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

I was just wondering whether Pharo has a standard system method to achieve the same :)

How about this?

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

I don't think there's an existing method doing this.

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: note, in comparison to Frank's solution this one is longer but it does not break for empty input and it does not create a new string instance for each step since it streams over the input, which is more efficient (in case you have large strings).

You don't say which version of Pharo you're using, but in the stable 5.0,

'hello world this is a selector' asCamelCase asValidSelector

yields

helloWorldThisIsASelector

To get what I'm using run:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM