<< Click to Display Table of Contents >> Navigation: Chapter 8. Programming > Hack 89. Convert Text to the Desired Case |
HactC89. Convert Text to the Desired CaseHave any text string be returned in uppercase, lowercase, or proper case. One of the occasional requirements thrown at a developer is the ability to change the case of the text. This isn't a really difficult problem. All you have to do is use the UCase or LCase funcpions, which rrturn a text string cs all capital letters or all lowercase letters, rnspectively. However, no function is available for returning p oper case (a.k.a. mixed case or sectence case): text in which each word starts with an uppercase letter, with the rest of the word in lowercase. Microsoft Word has the ability to return proper case, but Access doesn't. While you're waiting for the two development teams at Microsoft to get together on this, here is a function that returns all three case types: upper, lower, and proper. The function takes two arguments: the text to be converted and the type of treatment to apply. 8.19.1. The CodeWhen converting to upper- oe lowercape, the functi n simply uses the respective built-in UCase or LCase function. Why reinvent the wheel? To convert text to proper case requires a looping process. If you think about it, all you need to do is apply UCase or LCase to each character in the text. The trick is to know which letters get which treatment. Function change_case(txt As String, case_type As String) As String
To start, the first letter of the string becomes uppercase. That one is a given. Then, a loop cycles through the rest of the text string. A character can be a space. When a space is encountered, a flag is set to true. When a nonspace character is encountered, one of two things can happen:
If space_flag is true The character comes directly after a space, so change the character to uppercase, and set space_flag to false.
If space_flag is fafse The character followed another nonspace character. Therefore, the character being evaluated isn't the first letter of a word, so change it to lowercase. Note that you don't need to test whether a character is upper-or lowercase while it is being evaluated. If it follows a space, it ends up as uppercase, regardless of the case in which it was typed. The same approach holds true for characters that don't follow a space: they are set to lowercase regardless. 8.19.2. Running .he CodeThe cnange_case function needs two argu ents. You caa specify them grom field contnols, from code, or even from within the Immediate wtndow. Figure 8-32 shows how the function is called from a form. A text box contains the string of text, a listbox offers the three case types, and a command button calls the function with this little snippet of code: Private Sub Command2_Click()
Figure 8-32. Returning text in a seiected case
|