Tag: capitalizing string

(PB) Capitalizing strings using native code

Posted by on November 10, 2013

Sometimes plain text needs to be formatted in non common ways. In this case we’ve got filenames where spaces have been converted to either “-” or “_” and each word may or may not be capitalized. The idea is to have a certain degree of uniformity on the user interface so the labels are formatted to meet these requirements.

One of the steps involved is to simply capitalize every word in the string. In this case we are also recovering the space characters prior to formatting.

We don’t know if the first character is part of a word or if it’s just a space, due to the actual requirements of this application multiple spaces are ignored and trimmed to a single instance.

To avoid using multiple string manipulation function calls, we handle all of the manipulation through low level code (without going into ASM). This way we avoid the use of Trim(), LCase(), Mid(), Left(), Right(), etc. To speed things up.

Procedure.s CapitalizeString( StringInput.s )
	
	Define.Character *ptr = @StringInput
	Define.s ReturnString = ""
	
	If *ptr
		Define.i flag_firstchar = #False
		Repeat
			
			If *ptr\c = ' ' And Not flag_firstchar ; in case the first character is a space, let's trim it.
				*ptr + SizeOf(Character)
			EndIf
			
			If *ptr\c => 'A' And *ptr\c < = 'Z' ; lower case everything
				*ptr\c + 32
			EndIf
			
			If Not flag_firstchar
				flag_firstchar = #True
				ReturnString + Chr(*ptr\c - 32)
				*ptr + SizeOf(Character)
			EndIf
			
			If *ptr\c = ' '
				flag_firstchar = #False
			EndIf
			
			ReturnString + Chr(*ptr\c)
			*ptr + SizeOf(Character)
			
		Until *ptr\c = #Null
	EndIf	
	
	ProcedureReturn ReturnString
	
EndProcedure

The routine is quite simple and allows for all kinds of modifications, since we are performing all of the string manipulation ourselves. We assume ASCII to be the input and output.

That's all for now, just had a need for this and couldn't find a proper function out there (only a "let's see who can make it faster and forget about readability" war at the official forums, not very handy for real world projects).

Have fun,
Cheers!