现在的位置: 首页 > 设计导读 > 正文

【K&R C语言】第2章 类型、运算符与表达式

2011年04月13日 设计导读 ⁄ 共 367字 ⁄ 字号 暂无评论

类型、运算符与表达式是C语言中最基本的元素

2.3 常量 【A 实现字符串长度函数 strlen2.7 类型转换 
    【B 函数 atoi 字符串->整型数】
    【 C lower 转换成小写】
2.8 自增运算符与自减运算符 
    【D 函数squeeze 从字符串中删除字符 】
    【E 字符串拼接函数 strcat

2.3 常量 【实现字符串长度函数 strlen】

1
2
3
4
5
6
7
8
9
10
11
12
13
int strlen(char s[])
{
    int i = 0;
 
    while (s[i] != '\0')
        ++i;
    return i;
}
 
/* 这个函数是字符串操作的基本函数 
 #include <string.h>
  size_t strlen( char *str );
  */

2.7 类型转换

【函数 atoi 字符串->整型数】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* atoi: convert s to integer */
int atoi(char s[])
{
    int i, n;
 
    n = 0;
    for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
        n = 10 * n + (s[i] - '0');
    return n;
}
/* 这个函数在库函数中也有
#include <stdlib.h>
  int atoi( const char *str );
*/

【 lower 转换成小写】

1
2
3
4
5
6
7
8
9
10
11
12
13
/* lower: convert c to lower case; ASCII only */
int lower(int c)
{
    if (c >= 'A' && c <= 'Z')
        return c + 'a' - 'A';
    else
        return c;
}
/* 这个函数在库函数中的名字有所变化 tolower
#include <ctype.h>
  int tolower( int ch );
 
*/

2.8 自增运算符与自减运算符

【函数 squeeze 从字符串中删除字符 】

1
2
3
4
5
6
7
8
9
10
/* squeeze: delete all c from s */
void squeeze(char s[], int c)
{
    int i, j;
 
    for (i = j = 0; s[i] != '\0'; i++)
        if (s[i] != c)
            s[j++] = s[i];
    s[j] = '\0';
}

【字符串拼接函数 strcat】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* strcat: concatenate t to end of s; s must be big enough */
void strcat(char s[], char t[])
{
    int i =0,  j = 0;
 
    while (s[i] != '\0') /* find end of s */
        i++;
    while ((s[i++] = t[j++]) != '\0') /* copy t */
        ;
}
/*
#include <string.h>
  char *strcat( char *str1, const char *str2 );
*/

抱歉!评论已关闭.