1 /* 2 string_utilities.c 3 -------------- 4 Written By: Eu-Jin Goh 5 6 A bunch of useful functions that I keep using all the time. 7 */ 8 9 /* necessary header files and defines */ 10 11 #include <stdlib.h> 12 #include <stdio.h> 13 #include <string.h> 14 15 #include "string_utilities.h" 16 #include "general_utilities.h" 17 18 /* ------------- String Functions ----------------- */ 19 20 /* 21 wrapper around strcpy that allocates memory for the dest string 22 */ 23 char * utlstring_strcpy(const char * srcString)24utlstring_strcpy(const char *srcString) 25 { 26 char *destBuffer; 27 28 if(srcString == NULL) 29 { 30 fprintf(stderr, "utl_strcpy: NULL string passed as argument\n"); 31 return NULL; 32 } 33 34 destBuffer = utl_GetMem(strlen(srcString) + 1); 35 strcpy(destBuffer, srcString); 36 37 return destBuffer; 38 } 39 40 /* 41 wrapper around strcat that allocates memory for the concatenated string 42 */ 43 char * utlstring_strcat(const char * prefixString,const char * suffixString)44utlstring_strcat(const char *prefixString, const char *suffixString) 45 { 46 char *concat; 47 48 if(prefixString == NULL || suffixString == NULL) 49 { 50 return NULL; 51 } 52 53 concat = utl_GetMem(strlen(prefixString) + strlen(suffixString) + 1); 54 strcpy(concat, prefixString); 55 strcat(concat, suffixString); 56 57 return concat; 58 } 59 60 /* assumes that srand has already been called */ 61 char * utlstring_GenRandomString(const int size)62utlstring_GenRandomString(const int size) 63 { 64 char *result; 65 int rchar; 66 int i; 67 68 result = utl_GetMem(size + 1); 69 70 71 for(i = 0; i < size; i++) 72 { 73 /* first determine upper or lower case */ 74 rchar = rand() % 2; 75 76 if(rchar) 77 { 78 /* generate lower case */ 79 result[i] = (char) ((rand() % 26) + 'a'); 80 } 81 else 82 { 83 /* generate upper case */ 84 result[i] = (char) ((rand() % 26) + 'A'); 85 } 86 } 87 result[size] = '\0'; 88 89 return result; 90 } 91