String Processing
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[])
{
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[], char string2[]) //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[], char string2[])
{
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[], char string2[])
{
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;
}
本文深入解析了字符串处理的基础操作,包括字符串长度计算、复制、拼接及比较等关键算法。通过C语言实现,详细介绍了每种操作的具体实现方式,是理解和掌握字符串处理的重要资源。

被折叠的 条评论
为什么被折叠?



