简体   繁体   English

如何在Pharo中使用一个字符串?

[英]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. 而且我认为asCapitalizedPhrase asLegalSelector会做到这一点,但事实并非如此。

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: 我已经有办法将字符串转换为camelCase选择器:

|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 :) 我只是想知道Pharo是否有一个标准的系统方法来实现相同的:)

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). 编辑:注意,与Frank的解决方案相比,这个更长,但它不会因空输入而中断,并且它不会为每个步骤创建一个新的字符串实例因为它在输入上流动,这样更有效(如果你有大的话)字符串)。

You don't say which version of Pharo you're using, but in the stable 5.0, 你没有说你正在使用哪个版本的Pharo,但在稳定的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: 我知道这是旧的,但Squeak有一个有用的实现(String >> asCamelCase)基本上这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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