[Newbies] a titleize function?
David T. Lewis
lewis at mail.msen.com
Sat Mar 20 15:18:42 UTC 2010
I should note also that class Character has methods for testing
different kinds of characters (#isDigit and so forth). So if you
wanted your method to work for strings that might contain tab
characters or carriage returns as separator characters between
words, then you would use the #isSeparator test rather than looking
for space characters explicitly, like this:
"Answer a copy of myself with the first character of each word capitalized "
" 'a mouse ate cheese' titleize "
^ String streamContents: [:strm | self
inject: Character space
into: [:last :this | strm
nextPut: (last isSeparator
ifTrue: [this asUppercase]
On Sat, Mar 20, 2010 at 11:05:02AM -0400, David T. Lewis wrote:
> On Fri, Mar 19, 2010 at 02:31:40AM -0400, sergio_101 wrote:
> > is there a function that can do this:
> > 'a mouse ate cheese' . 'A Mouse Ate Cheese'
> > i found capitlize, but that only hits the first word..
> Here is another way to do it:
> "Answer a copy of myself with the first character of each word capitalized "
> " 'a mouse ate cheese' titleize "
> ^ String streamContents: [:strm | self
> inject: Character space
> into: [:last :this | strm
> nextPut: (last = Character space
> ifTrue: [this asUppercase]
> ifFalse: [this])]]
> The #inject:into: steps through the string, keeping track of the
> preceding character and writing the current character to a stream,
> converting it to upper case if the preceding character was a space.
> The result of the #nextPut: is the character we wrote, which appears
> in the #last variable each time we step through the loop.
> The #streamContents: method provides the stream that we write the
> characters to, and answers the resulting string when complete.
More information about the Beginners