# 非常经典的C字符串函数的实现

2014/10/31 17:49

``1. strlen(),计算字符串长度``
`````` 1 int strlen(const char string)
2
3 {
4
5     int i=0;
6
7     while(string[i]) i++;
8
9     return i;
10
11 }``````
``2. strcpy(), 字符串拷贝.``
``````1 char *strcpy(char *destination, const char *source)
2
3 {
4
5     while(*destinaton++=*source++);
6
7     return (destination-1);
8
9 }``````
``3. strcat(), 字符串的连接.``
`````` 1 char *strcat(char *target,const char *source)
2
3 {
4
5     char *original=target;
6
7     while(*target) target++; // Find the end of the string
8
9     while(*target++=*source++);
10
11     return(original);
12
13 }``````
``4. streql(), 判断两个字符串是否相等.``
`````` 1 int streql(char *str1,char *str2)
2
3 {
4
5     while((*str1==*str2)&&(*str1))
6
7     {
8
9         str1++;
10
11         str2++;
12
13     }
14
15     return((*str1==NULL)&&(*str2==NULL));
16
17 }``````
``5. strchr(), 在字符串中查找某个字符.``
`````` 1 char *strchr(const char *string,int letter)
2
3 {
4
5     while((*string!=letter)&(*string))
6
7         string++;
8
9     return (string);
10
11 }``````
``6. chrcnt(), 计算某个字符在字符串中出现的次数.``
`````` 1 int chrcnt(const char *string,int letter)
2
3 {
4
5     int count=0;
6
7     while(*string)
8
9         if(*string==letter)count++;
10
11     return count;
12
13 }``````
``7. strcmp(), 判断两个字符串是否相等.``
`````` 1 int strcmp(const char *str1,const char *str2)
2
3 {
4
5     while((*str1==*str2)&&(*str1))
6
7     {
8
9         str1++;
10
11         str2++;
12
13     }
14
15     if((*str1==*str2)&&(!*str1)) //Same strings
16
17         return o;
18
19     else if((*str1)&&(!*str2)) //Same but str1 longer
20
21         return -1;
22
23     else if((*str2)&&(!*str1)) //Same but str2 longer
24
25     else
26
27     return((*str1>*str2)?-1:1);
28
29 }``````

0
0 收藏

0 评论
0 收藏
0