Change Case of a String in a Fast, Optimized way
writing a loop to check each character and then perform certain function on them. Doing that not just increases lines of code but also time complexity.
In this article I present some special cases where you do NOT need to write a loop for some string operations. With the use of tricky bit operations on strings, the time complexity of the existing algorithms can be reduced by many folds. Since they perform operations in O (1) time complexity, they are arguably the fastest string operations. In the end we will also do a comparison of the various methods to see how fast it really is.
Basic idea: A string can be converted to lower case using simple bit operations on each character. To understand this, let us take an example. Suppose we want to convert “AppLe” into lower case. The different characters in the word are stored in the following format in the memory:
Char Dec Bin
A 65 01000001
p 112 01110000
p 112 01110000
L 76 01001100
e 101 01100101
Now, if we analyze the binary codes of the various characters, we see that the third bit from left, in an 8-bit string is 0 for UPPER case letters and 1 for lower case letters. And that would be our trick!
All we have to do now is set this bit 1 if we need lower case letters and 0 if we need upper case letters.
Implementation: Implementing this also pretty straightforward. We use the BINARY OR operator to do this. The Here is some sample code:
#include<stdio.h> int main() { char capsLetter = ‘A’; // ’A’ in binary is 01000001 char mask = (char) 32; // 32 in binary is 00100000 printf(“The caps letter ‘%c’ ”, capsLetter); capsLetter | = mask; // ‘a’ in binary is 01100001 – result printf(“is converted to ‘%c’.”, capsLetter); return 0; }
Output:
The caps letter ‘A’ is converted to ‘a’.
2 Responses
[…] Change Case of strings in a Highly Optimized way. […]
[…] Change Case of strings in a Highly Optimized way. […]