[Newbies] a titleize function?

David T. Lewis lewis at mail.msen.com
Sat Mar 20 15:05:02 UTC 2010


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:

String>>titleize
    "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])]]

Explanation:

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.

A change set is attached.

Dave

-------------- next part --------------
'From Squeak3.11alpha of 20 March 2010 [latest update: #9743] on 20 March 2010 at 11:51:15 am'!
"Change Set:		String-titleize-dtl
Date:			20 March 2010
Author:			David T. Lewis

'a mouse ate cheese' titleize ==> 'A Mouse Ate Cheese'

An example implementation of String>>titleize. The method is in category *examples so that it will not be treated as part of the Collections package. If you implement this method as part of your application in category MyApp, then this method can be put into method category *myApp."!


!String methodsFor: '*examples' stamp: 'dtl 3/20/2010 11:45'!
titleize
	"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])]]! !


!String reorganize!
('accessing' byteAt: byteAt:put: byteSize do:toFieldNumber: endsWithDigit findAnySubStr:startingAt: findBetweenSubStrs: findCloseParenthesisFor: findDelimiters:startingAt: findLastOccurrenceOfString:startingAt: findString: findString:startingAt: findString:startingAt:caseSensitive: findTokens: findTokens:escapedBy: findTokens:includes: findTokens:keep: findWordStart:startingAt: includesSubString: includesSubstring:caseSensitive: indexOf: indexOf:startingAt: indexOf:startingAt:ifAbsent: indexOfSubCollection: indexOfSubCollection:startingAt:ifAbsent: lastIndexOfPKSignature: leadingCharRunLengthAt: lineCorrespondingToIndex: lineCount lineIndicesDo: lineNumber: linesDo: skipAnySubStr:startingAt: skipDelimiters:startingAt: startsWithDigit string tabDelimitedFieldsDo:)
('arithmetic' * + - / // \\)
('comparing' < <= = > >= alike: caseInsensitiveLessOrEqual: caseSensitiveLessOrEqual: charactersExactlyMatching: compare: compare:caseSensitive: compare:with:collated: crc16 endsWith: endsWithAnyOf: hash hashMappedBy: hashWithInitialHash: howManyMatch: match: sameAs: startingAt:match:startingAt:)
('converting' , adaptToCollection:andSend: adaptToNumber:andSend: adaptToPoint:andSend: adaptToString:andSend: asAlphaNumeric:extraChars:mergeUID: asByteArray asByteString asCharacter asDate asDateAndTime asDecomposedUnicode asDisplayText asDuration asFileName asFourCode asHex asHtml asIdentifier: asInteger asLegalSelector asLowercase asNumber asOctetString asPacked asPluralBasedOn: asPrecomposedUnicode asSignedInteger asSmalltalkComment asSqueakPathName asString asStringOrText asSymbol asText asTime asTimeStamp asUnHtml asUnsignedInteger asUppercase asUrl asUrlRelativeTo: asVmPathName askIfAddStyle:req: asWideString base64Decoded base64Encoded capitalized compressWithTable: contractTo: convertFromEncoding: convertFromSuperSwikiServerString convertFromWithConverter: convertToEncoding: convertToSuperSwikiServerString convertToSystemString convertToWithConverter: correctAgainst: correctAgainst:continuedFrom: correctAgainstDictionary:continuedFrom: encodeForHTTP encodeForHTTPWithTextEncoding: encodeForHTTPWithTextEncoding:conditionBlock: findSelector initialIntegerOrNil keywords numericSuffix onlyLetters romanNumber sansPeriodSuffix splitInteger squeakToUtf8 stemAndNumericSuffix subStrings subStrings: substrings surroundedBySingleQuotes translateFrom:to:table: translateToLowercase translateToUppercase translateWith: truncateTo: truncateWithElipsisTo: unescapePercents unescapePercentsWithTextEncoding: unparenthetically unzipped utf8ToSqueak withBlanksCondensed withBlanksTrimmed withFirstCharacterDownshifted withNoLineLongerThan: withoutJustTrailingDigits withoutLeadingBlanks withSeparatorsCompacted withoutLeadingDigits withoutTrailingBlanks withoutTrailingDigits zipped)
('copying' copyReplaceTokens:with: deepCopy padded:to:with:)
('displaying' displayAt: displayOn: displayOn:at: displayOn:at:textColor: displayProgressAt:from:to:during:)
('encoding' getInteger32: putInteger32:at: writeLeadingCharRunsOn:)
('filter streaming' byteEncode: putOn:)
('formatting' expandMacros expandMacrosWithArguments: expandMacrosWith: expandMacrosWith:with: expandMacrosWith:with:with: expandMacrosWith:with:with:with: format: withCRs)
('internet' decodeMimeHeader decodeQuotedPrintable isoToSqueak isoToUtf8 macToSqueak squeakToIso squeakToMac utf8ToIso withInternetLineEndings withSqueakLineEndings withUnixLineEndings withoutQuoting)
('paragraph support' indentationIfBlank:)
('printing' encodeDoublingQuoteOn: isLiteral printOn: storeOn: stringRepresentation)
('system primitives' endsWithAColon findSubstring:in:startingAt:matchTable: numArgs)
('testing' includesUnifiedCharacter isAllDigits isAllSeparators isAsciiString isByteString isOctetString isString isWideString lastSpacePosition)
('translating' translated translatedIfCorresponds translatedTo:)
('user interface' asExplorerString openInWorkspaceWithTitle:)
('*Morphic' asMorph asStringMorph)
('*MorphicExtras-*morphic-Postscript Canvases' asPostscript)
('*Morphic-converting' openAsMorph)
('*monticello' extractNumber)
('*network-uri' asURI)
('*packageinfo-base' escapeEntities)
('*services-base' service serviceOrNil)
('*versionnumber' asVersion)
('private' correctAgainstEnumerator:continuedFrom: evaluateExpression:parameters: replaceFrom:to:with:startingAt: stringhash)
('*universes-model' uversionEqual: uversionLessThan:)
('*Universes' asUVersion)
('*Morphic-Explorer' hasContentsInExplorer)
('deprecated-3.10' findLastOccuranceOfString:startingAt:)
('*xml-parser' applyLanguageInfomation:)
('*VMMaker-Translation to C' replaceLastOccurrence:with:)
('*Etoys-tiles' basicType newTileMorphRepresentative)
('*ST80-Support' asParagraph)
('*system' suggestedTypeNames)
('*examples' titleize)
!



More information about the Beginners mailing list