Length of String
Because strings are ending with a '\0', just searching '\0' in a string and the index of '\0' is same as the number of charaters before '\0'.
int myStrLen(char s[LSIZE])
{
int i=0;
while (s[i]) //same as s[i]!='\0'
i++;
return i;
}
Copying String
Array assignment is not permitted in C. Therefore, we must copy array element one by one. A loop will solve the problem.
void myStrCpy(char string1[LSIZE], char string2[LSIZE]) //copying string2 to string1
{
int i = 0;
while (string2[i])
{
string1[i] = string2[i];
i++;
}
string1[i] = '\0';
}
Note: after having copied all charaters of string2 to string1, we should put an end-of-string '\0' at the end of string1.
String Concatenation
While copying string2 to string1 will erase all charaters in string1, concatenation will copy string2 at the end of string1.
void myStrConcat(char string1[LSIZE], char string2[LSIZE])
{
int i=0;
int j=0;
while(string1[i])
i++;
while(string2[j])
{
string1[i+j] = (string2[j]);
j++;
}
string1[i+j] = '\0';
}
String Comparison
Compare two strings as in dictionary. The order of characters are base on the ASCII codes of the characters.
int myStrCmp(char string1[LSIZE], char string2[LSIZE])
{
int i=0;
while (string1[i] && string2[i] && string1[i] == string2[i])
i++;
if (string1[i] == string2[i])
return 0;
else if (string1[i] < string2[i])
return -1;
else
return 1;
}