Although the C language has char arrays and corresponding methods for them, it's vulnerable for some functions such as gets() and strcpy which could cause stack buffer overflow. We could encapsulate them and define our own strings in C language. Here's the definition of data structure String:
typedef struct String {
char* str;
int length;
} String;
Create String
To create a string, we get the dynamic memory for it flooding with '\0' and set the length.
int createString(String* string, int length) {
string->str = (char*)malloc((length + 1)*sizeof(char));
memset(string->str, '\0', length + 1);
string->length = length;
return 0;
}
Set String
set the content of a string, this could also used for string copy.
int setString(String dest, char* str, int length) {
int cnt = 0;
if (NULL == dest.str || NULL == str)
return -1;
while (cnt < dest.length && cnt < length)
dest.str[cnt] = str[cnt++];
return 0;
}
Sub String
Get the sub string of the origin string from any position.
int subString(String dest, String src, int pos, int length) {
int cnt = 0;
if (NULL == dest.str || length > dest.length)
return -1;
while (cnt < length)
dest.str[cnt++] = src.str[pos - 1 + cnt];
return 0;
}
Concatenate String
Concatenate two strings into a new string.
int concatString(String dest, String s1, String s2) {
int i = 0, j = 0;
if (NULL == dest.str || NULL == s1.str || NULL == s2.str)
return -1;
if (dest.length < s1.length + s2.length)
return -1;
while (i < s1.length && '\0' != s1.str[i])
dest.str[i] = s1.str[i++];
while (j < s2.length && '\0' != s2.str[j])
dest.str[i++] = s2.str[j++];
return 0;
}
Compare String
Compare two strings. If they are the same, return 0. Then return the result of whose ascii codes' comparison
int compareString(String s1, String s2) {
int cnt = 0;
if (s1.length > s2.length)
return 1;
else if (s1.length < s2.length)
return -1;
else {
while (cnt < s1.length && cnt < s2.length && s1.str[cnt] != s2.str[cnt++])
return (s1.str[cnt] > s2.str[cnt]) ? 1 : -1;
}
}
Destroy
Free the dynamic memory for the string.
void destoryString(String string) {
if (NULL == string.str)
return;
free(string.str);
}