欢迎光临
我们一直在努力

字符函数和字符串函数(一)

一、字符分类函数

1.1字符分类函数

   C语言中有一系列的函数是专门做字符分类的,也就是一个字符是属于什么类型的字符的,这些函数的使用都需要包含一个头文件ctype.h

1.2举例

int tolower ( int c );//将大写字母转换为小写字母(函数)

islower是判断参数部分是否为小写字母

练习:将字符串中的小写字母转化成大写,其他字符不变

代码如下,可自行测试

#include <stdio.h>
#include <ctype.h>
int main()
{
    int i = 0;
    char str[] = "THIS IS AN APPLE\\n";
    char c;
    while (str[i])
    {
        c = str[i];
        putchar(tolower(c));
        i++;
    }
    return 0;
}

二、字符转换函数

2.1.C语言提供了2个字符转换函数

int tolower ( int c );//将大写字母转换为小写字母(函数)

int toupper ( int c );//将小写字母转换为大写字母(函数)

2.2.举例

代码如下,可自行测试

#include <stdio.h>
#include <ctype.h>
int main()
{
    int i = 0;
    char str[] = "This is an apple\\n";
    char c;
    while (str[i])
    {
        c = str[i];
        putchar(toupper(c));
        i++;
    }
    return 0;
}

三、strlen的使用和模拟实现

3.1.size_t strlen ( const char * str );

作用:返回字符串 str 的长度

    C字符串的长度由终止空字符决定:C字符串的长度等于从字符串开始到终止空字符之间的字符数量(不包括终止空字符本身)。

    这不应与存储字符串的数组大小相混淆。例如:char mystr[100] = \\"test string\\";

    定义了一个大小为100个字符的字符数组,但mystr初始化的C字符串长度仅为11个字符。因此,虽然sizeof(mystr)的值为100,而strlen(mystr)返回11。

在C++中,char_traits::length实现了相同的行为。

3.2方式一:计数器实现

测试代码如下:

#include<stdio.h>
#include<string.h>
#include<assert.h>
int my_strlen(const char *s1) {
    int count = 0;
    assert(s1 != NULL);
    while (*s1) {
        s1++;
        count++;
    }
    return count;
}
int main() {
    const char* s1 = "abcdef";
    int len = my_strlen(s1);
    printf("%d", len);
    return 0;
}

3.3.方式二:不使用计数器

代码如下:可自行测试

#include<stdio.h>
#include<string.h>
#include<assert.h>
int my_strlen(const char* s1) {
    assert(s1 != NULL);
    if (*s1 == '\\0')
        return 0;
    else
    return 1 + strlen(s1 + 1);
}
int main() {
    const char* s1 = "abcdef";
    int len = my_strlen(s1);
    printf("%d", len);
    return 0;
}

3.4.指针-指针

运行结果如下:

测试代码如下:

#include<stdio.h>
#include<string.h>
#include<assert.h>
int my_strlen(const char* s1) {
    assert(s1 != NULL);
    char* p = s1;
    while (*p != '\\0') 
        p++;     
    return p – s1;
}
int main() {
    const char* s1 = "abcdef";
    int len = my_strlen(s1);
    printf("%d", len);
    return 0;
}

    肝文不易,全是掏心窝的干货~动动小手点个关注,后续精彩不迷路,一起唠干货涨知识,你的关注就是我爆更的动力~

赞(0)
未经允许不得转载:171主机测评 » 字符函数和字符串函数(一)
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址