Vanilla C with Sprinkles – Useful String Functions
making your life easier with basic string functions in vanilla c
Published by Ryan Boucher @ 11:55 pm
Service testing is made so much easier if you have some basic string functionality to assist you. C isn’t spectacular with strings so we need to write most of the basic stuff ourself.
Here are some of my favourite string functions for use within service tests.
Get Random String of Length
enum GetStringOfLengthTypes
{
AlphaOnly,
NumericOnly,
AlphaNumeric
} ;
const char* GetStringOfLength (const unsigned int length, const unsigned int Type)
{
unsigned int i = 0 ;
static const char Alpha[] = "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const char Numeric[] = "0123456789" ;
static const char AlphaNumeric[] = "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789" ;
char* Value = (char*) malloc ( (sizeof(char) * length) + 1) ;
SrandSingleton is a global integer that is defaulted to zero. It represents a ’singleton’ object.
if (SrandSingleton == 0)
{
srand (time (NULL)) ;
SrandSingleton = 1 ;
}
for (i = 0; i < length; i++)
{
switch (Type)
{
case 0:
Value[i] = Alpha[rand() % (sizeof (Alpha) - 1)] ;
break ;
case 1:
Value[i] = Numeric[rand() % (sizeof (Numeric) - 1)] ;
break ;
case 2:
Value[i] = AlphaNumeric[rand() % (sizeof (AlphaNumeric) - 1)] ;
break ;
}
}
Value[length] = '\0' ;
lr_get (Value, "__GetStringOfLength_Total") ;
free (Value) ;
return lr_get ("{__GetStringOfLength_Total}") ;
}
String is Empty?
enum EnabledOptions StringIsEmpty (const char* const a)
{
if (strcmp (a, "") == '\0')
{
return Yes ;
}
else
{
return No ;
}
}
Strings are Equal?
enum EnabledOptions StringsAreEqual (const char* const a, const char* const b)
{
if (strcmp (a, b) == '\0')
{
return Yes ;
}
else
{
return No ;
}
}
Is In String?
enum EnabledOptions IsInString (const char* const Source, const char* const Find)
{
if (strstr (Source, Find) == 0)
{
return No ;
}
else
{
return Yes ;
}
}
|
|
Ryan Boucher is a Software Inquisitor and is passionate about it. You can find a whole raft of articles and anecdotes about software testing and other topics he gets excited about. |
| Tags |