Monday, July 12, 2010

Random String Function Implementations

There are a bunch of string functions out-there that do almost everything you could want to do with strings.

There's so much however that sometimes its just simpler to implement your own method instead of finding the appropriate function to use.

What if you wanted to find the size of a char-array string including its NULL-byte.
Well you can easily and elegantly do this:

int strSize(const char* str) {
int len = 0;
return len;

Another easy thing to implement is a toLower() function which converts uppercase letters to lowercase:

void strToLower(char* str) {
for( ; *str; str++) {
char& c = *str;
if (c >= 'A' && c <= 'Z') c = c - 'A' + 'a';

A matching toUpper() function is obviously just as easy ;p

Last here's a fun function I made that converts a 'u32' (unsigned 32-bit integer), to a hex string:

string toHexString(u32 value) {
char str9[9];
u32 pos = 0;
for (int i = 0; i < 8; i++) {
char dig = (value>>((7-i)*4))&0xf;
if (!dig && !pos) continue;
if ((dig) < 0xa) str9[pos] = '0' + dig;
else str9[pos] = 'a' +(dig-0xa);
if (!pos) { str9[0] = '0'; pos=1; }
str9[pos] = '\0';
return string(str9);

That one is definitely more complex than the others, but it was fun to code.
All hex digits are 4-bits, and a u32 value only needs a char array of at-most size 9 (8 digits + 1 null byte).

Anyways, in real coding projects its probably best to use already defined functions that perform the string operation you want; but implementing your own can sometimes be fun, and possibly impress your professors on homework assignments.

No comments:

Post a Comment