现在的位置: 首页 > 基础课程 > 正文

C语言课程期终复习(下)

2011年06月11日 基础课程 ⁄ 共 1623字 ⁄ 字号 暂无评论

3-D【倒置字符串 reverse】

1
2
3
4
5
6
7
void reverse(char s[])                  /* (char *s) */
{
    int c, i, j;
    for (i = 0, j = strlen(s)-1; i < j; i++, j--) {
        c = s[i];  s[i] = s[j];  s[j] = c;
    }
}

倒置数组也是一样的,只不过将参数 char s[] 改成 int s[] 或 v[]

1
2
3
4
5
6
7
void reverse(int v[], int n)
{
    int c, i, j;
    for (i = 0, j = n-1; i < j; i++, j--) {
        c = v[i];  v[i] = v[j];  v[j] = c;
    }
}

3-E【itoa 将数字n转换为字符串并保持到 s 中】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void itoa(int n, char s[])       /*  -123 ->  “-123” */
{
    int i = 0, sign;
 
    if ((sign = n) < 0) 
        n = -n;
 
    do {               /* get digits in reverse order */
        s[i++] = n % 10 + '0'; 
    } while ((n /= 10) > 0); 
 
    if (sign < 0)
        s[i++] = '-';
    s[i] = '\0';
    reverse(s);
}

3-F【trim函数:删除字符串尾部的空格符、制表符与换行符】

1
2
3
4
5
6
7
8
9
10
int trim(char s[])
{
    int n;
 
    for (n = strlen(s)-1; n >= 0; n--)
        if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n')
            break;
    s[n+1] = '\0';
    return n;                       /* the length of s */
}

抱歉!评论已关闭.