【C语言】11.字符函数和字符串函数

news2024/10/6 8:24:19

文章目录

  • 1.字符分类函数
  • 2.字符转换函数
  • 3.strlen的使用和模拟实现
  • 4.strcpy的使用和模拟实现
  • 5.strcat的使用和模拟实现
  • 6.strcmp的使用和模拟实现
  • 7.strncpy函数的使用
  • 8.strncat函数的使用
  • 9.strncmp函数的使用
  • 10.strstr的使用和模拟实现
  • 11.strtok函数的使用
  • 12.strerror函数的使用


1.字符分类函数

C语言中有一系列的函数是专门做字符分类的,也就是一个字符是属于什么类型的字符的。

这些函数的使用都需要包含一个头文件是 ctype.h

在这里插入图片描述

我们来看一下其中一个:

int islower ( int c );

islower 是能够判断参数部分的 c 是否是小写字母的。

通过返回值来说明是否是小写字母,如果是小写字母就返回非0的整数,如果不是小写字母,则返回0。

#include <stdio.h>
#include <ctype.h>
int main() {
	int ret = islower('A');
	printf("%d\n", ret);
	return 0;
}

打印:

0

练习:

写一个代码,将字符串中的小写字母转大写,其他字符不变。

int main() {
	char arr[] = "I am a Student.";
	int i = 0;
	while (arr[i] != '\0') {
		if (islower(arr[i])) {
			arr[i] = arr[i] - 32;
		}
		i++;
	}
	printf("%s\n", arr);
	return 0;
}

打印:

I AM A STUDENT.

2.字符转换函数

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

int tolower ( int c ); //将参数传进去的大写字母转小写 
int toupper ( int c ); //将参数传进去的小写字母转大写

例子:

#include <stdio.h>
#include <ctype.h>
int main ()
{
    int i = 0;
    char str[] = "Test String.\n";
    char c;
    while (str[i])
    {
        c = str[i];
        if (islower(c)) 
            c = toupper(c);
        putchar(c);
        i++;
    }
    return 0;
}

打印:

TEST STRING.

3.strlen的使用和模拟实现

size_t strlen ( const char * str );
  1. 字符串以 ‘\0’ 作为结束标志,strlen函数返回的是在字符串中 ‘\0’ 前面出现的字符个数(不包含 ‘\0’ )。

  2. 参数指向的字符串必须要以 ‘\0’ 结束。

  3. 注意函数的返回值为 size_t,是无符号的( 易错 )

  4. strlen的使用需要包含头文件

  5. 学会strlen函数的模拟实现

strlen的模拟实现:

1.计数器方式

int my_strlen(const char * str)
{
    int count = 0;
    assert(str);//断言
    while(*str)
    {
        count++;
        str++;
    }
    return count;
}

2.不能创建临时变量计数器

int my_strlen(const char * str)
{
    assert(str);//断言
    if(*str == '\0')
        return 0;
    else
        return 1 + my_strlen(str+1);
}

3.指针-指针的方式

int my_strlen(char *s)
{
    assert(str);//断言
    char *p = s;
    while(*p != '\0' )
        p++;
    return p-s;
}

4.strcpy的使用和模拟实现

char* strcpy(char * destination, const char * source );
  1. Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).

    将源指向的 C 字符串复制到目标指向的数组中,包括终止 null 字符(并在此时停止)。

  2. 源字符串必须以 ‘\0’ 结束。

  3. 会将源字符串中的 ‘\0’ 拷贝到目标空间。

  4. 目标空间必须足够大,以确保能存放源字符串。

  5. 目标空间必须可修改。

  6. 学会模拟实现。

//这里的char*是为了实现链式访问
//strcpy函数返回的是目标空间的起始地址。
#include <stdio.h>
#include <assert.h>

char* my_strcpy(char* dest, const char* src)
{
    assert(dest && src);
    char* ret = dest;
    while (*src!='\0'){
        *dest = *src;
        src++;
        dest++;
    }
    *dest = *src;

    return ret;
}

int main() {
    char arr1[] = "abcdef";
    char arr2[20] = { 0 };

    my_strcpy(arr2, arr1);
    printf("%s\n", arr2);

	return 0;
}

打印:

abcdef

5.strcat的使用和模拟实现

  1. Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.

    将源字符串的副本追加到目标字符串。终止 null 字符 in destinationsource 的第一个字符覆盖,并且包含一个 null 字符在由目标中两者的串联形成的新字符串的末尾。

  2. 源字符串必须以 ‘\0’ 结束。

  3. 目标字符串中也得有 \0 ,否则没办法知道追加从哪里开始。

  4. 目标空间必须有足够的大,能容纳下源字符串的内容。

  5. 目标空间必须可修改。

  6. 字符串自己给自己追加,如何?

char* my_strcat(char* dest, const char* src)
{
    char* ret = dest;
    assert(dest != NULL);
    assert(src != NULL);
    while (*dest)
    {
        dest++;
    }
    while ((*dest++ = *src++))
    {
        ;
    }
    return ret;
}

int main() {
    char arr1[20] = "hello ";
    char arr2[] = "world";

    my_strcat(arr1, arr2);//字符串追加
    printf("%s\n", arr1);

    return 0;
}

打印:

hello world

6.strcmp的使用和模拟实现

  1. This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.

    此函数开始比较每个字符串的第一个字符。如果它们彼此相等,则继续执行以下对,直到字符不同或达到终止 null 字符。

  2. 标准规定:

  • 第一个字符串大于第二个字符串,则返回大于0的数字

  • 第一个字符串等于第二个字符串,则返回0

  • 第一个字符串小于第二个字符串,则返回小于0的数字

  • 那么如何判断两个字符串? 比较两个字符串中对应位置上字符ASCII码值的大小。

int my_strcmp(const char* str1, const char* str2)
{
    int ret = 0;
    assert(str1 != NULL);
    assert(str2 != NULL);
    while (*str1 == *str2)
    {
        if (*str1 == '\0')
            return 0;
        str1++;
        str2++;
    }
    return *str1 - *str2;
}

int main() {
    char arr1[] = "abq";
    char arr2[] = "abcdef";
    int ret = my_strcmp(arr1, arr2);
    printf("%d\n", ret);

    return 0;
}

打印:

14

7.strncpy函数的使用

 char * strncpy ( char * destination, const char * source, size_t num );
  1. Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.

    将源的前 num 个字符复制到目标。如果在复制 num 个字符之前找到源 C 字符串的末尾(由 null 字符表示),则 destination 将用零填充,直到将 num 个字符写入该字符串。

  2. 拷贝num个字符从源字符串到目标空间。

  3. 如果源字符串的长度小于num,则拷贝完源字符串之后,在目标的后边追加0,直到num个。

int main() {
	char arr1[20] = "abcdef";
	char arr2[20] = "xxxxxxxxxx";

	strncpy(arr2, arr1, 3);
	printf("%s\n", arr2);

	return 0;
}

打印:

abcxxxxxxx
int main() {
	char arr1[20] = "abcdef";
	char arr2[20] = "xxxxxxxxxx";

	strncpy(arr2, arr1, 8);
	printf("%s\n", arr2);

	return 0;
}

打印:

abcdef//这里多的两个位置会补\0

8.strncat函数的使用

char * strncat ( char * destination, const char * source, size_t num );
  1. Appends the first num characters of source to destination, plus a terminating null-character.

    (将source指向字符串的前num个字符追加到destination指向的字符串末尾,再追加一个 \0 字符)。

  2. If the length of the C string in source is less than num, only the content up to the terminating null-character is copied.

    (如果source 指向的字符串的长度小于num的时候,只会将字符串中到\0 的内容追加到destination指向的字符串末尾)。

#include <stdio.h>
#include <string.h>
int main ()
{
    char str1[20];
    char str2[20];
    strcpy (str1,"To be ");
    strcpy (str2,"or not to be");
    strncat (str1, str2, 6);
    printf("%s\n", str1);
    return 0;
}

打印:

To be or not

9.strncmp函数的使用

int strncmp ( const char * str1, const char * str2, size_t num );

比较str1str2的前num个字符,如果相等就继续往后比较,最多比较num个字母,如果提前发现不一样,就提前结束,大的字符所在的字符串大于另外一个。如果num个字符都相等,就是相等返回0.

在这里插入图片描述


10.strstr的使用和模拟实现

 char * strstr ( const char * str1, const char * str2);

功能:在str1中找str2这个字符串第一次出现的位置。

如果找到了,就返回这个第一次出现的起始地址。

如果没找到,就返回NULL这样一个空指针。

  1. Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.

    (函数返回字符串str2在字符串str1中第一次出现的位置)。

  2. The matching process does not include the terminating null-characters, but it stops there.

    (字符串的比较匹配不包含 \0 字符,以 \0 作为结束标志)。

#include <stdio.h>
#include <string.h>
int main ()
{
    char str[] ="This is a simple string";
    char * pch;
    pch = strstr (str,"simple");
    strncpy (pch,"sample",6);
    printf("%s\n", str);
    return 0;
} 

打印:

This is a sample string

strstr的模拟实现:

char * strstr (const char * str1, const char * str2)
{
    char *cp = (char *) str1;
    char *s1, *s2;
    if ( !*str2 )
        return((char *)str1);
    while (*cp)
    {
        s1 = cp;
        s2 = (char *) str2;
        while ( *s1 && *s2 && !(*s1-*s2) )
            s1++, s2++;
        if (!*s2)
            return(cp);
        cp++;
    }
    return(NULL);
}

11.strtok函数的使用

char * strtok ( char * str, const char * sep);
  1. sep参数指向一个字符串,定义了用作分隔符的字符集合

    例如:123456@qq.com

    里面的@.就是分隔符。

  2. 第一个参数指定一个字符串,它包含了0个或者多个由sep字符串中一个或者多个分隔符分割的标记。

  3. strtok函数找到str中的下一个标记,并将其用 \0 结尾,返回一个指向这个标记的指针。

    (注:strtok函数会改变被操作的字符串,所以被strtok函数切分的字符串一般都是临时拷贝的内容并且可修改。)

    例如:123456@qq.com

    会把@改成\0,然后返回一个指向1的地址。

  4. strtok函数的第一个参数不为 NULL ,函数将找到str中第一个标记,strtok函数将保存它在字符串中的位置。

  5. strtok函数的第一个参数为 NULL ,函数将在同一个字符串中被保存的位置开始,查找下一个标记。

  6. 如果字符串中不存在更多的标记,则返回 NULL 指针。

#include <stdio.h>
#include <string.h>
int main()
{
    char arr[] = "192.168.6.111";
    char* sep = ".";
    char* str = NULL;
    for (str = strtok(arr, sep); str != NULL; str = strtok(NULL, sep))
    {
        printf("%s\n", str);
    }
    return 0;
}

打印:

192
168
6
111

12.strerror函数的使用

char* strerror ( int errnum );

strerror 函数可以把参数部分错误码对应的错误信息的字符串地址返回来。

在不同的系统和C语言标准库的实现中都规定了一些错误码,一般是放在 errno.h 这个头文件中说明的,C语言程序启动的时候就会使用一个全局的变量errno来记录程序的当前错误码,只不过程序启动的时候errno是0,表示没有错误,当我们在使用标准库中的函数的时候发生了某种错误,就会将对应的错误码,存放在errno中,而一个错误码的数字是整数很难理解是什么意思,所以每一个错误码都是有对应的错误信息的。strerror函数就可以将错误对应的错误信息字符串的地址返回。

#include <stdio.h>
#include <string.h>
#include <errno.h>
//我们打印一下0~10这些错误码对应的信息
int main()
{
    int i = 0;
    for (i = 0; i <= 10; i++) {
        printf("%s\n", strerror(i));
    }
    return 0;
}

在Windows11+VS2022环境下输出的结果如下:

No error
Operation not permitted
No such file or directory
No such process
Interrupted function call
Input/output error
No such device or address
Arg list too long
Exec format error
Bad file descriptor
No child processes

上面就是0~10对应的错误码。

举例:

#include <stdio.h>
#include <string.h>
#include <errno.h>
int main()
{
    FILE* pFile;
    //打开文件
    pFile = fopen("unexist.ent", "r");//“r”以读文件的形式打开文件,如果这个文件不存在就打开失败,打开失败会返回一个空指针
    if (pFile == NULL) {
        printf("打开文件失败,原因是: %s\n", strerror(errno));
        return 1;
    }
    else {
        printf("打开文件成功\n");
        fclose(pFile);
        pFile = NULL;
    }
    return 0;
}

打印:

打开文件失败,原因是: No such file or directory

strerror:将错误码对应的错误信息的字符串的起始地址返回

perror:将errno中错误对应的错信息打印出来。

​ 先打印str指向的字符串,打印,然后打印一个空格,再打印错误码对应的错误信息

也可以了解一下 perror 函数,perror函数相当于一次将上述代码中的第10行完成了,直接将错误信息打印出来。perror函数打印完参数部分的字符串后,再打印一个冒号和一个空格,再打印错误信息。

#include <stdio.h>
#include <string.h>
#include <errno.h>
int main()
{
    FILE* pFile;
    //打开文件
    pFile = fopen("unexist.ent", "r");//“r”以读文件的形式打开文件,如果这个文件不存在就打开失败,打开失败会返回一个空指针
    if (pFile == NULL) {
        perror("打开文件失败,原因是");
        return 1;
    }
    else {
        printf("打开文件成功\n");
        fclose(pFile);
        pFile = NULL;
    }
    return 0;
}

打印:

打开文件失败,原因是: No such file or directory

perror:将errno中错误对应的错信息打印出来。

​ 先打印str指向的字符串,打印,然后打印一个空格,再打印错误码对应的错误信息

也可以了解一下 perror 函数,perror函数相当于一次将上述代码中的第10行完成了,直接将错误信息打印出来。perror函数打印完参数部分的字符串后,再打印一个冒号和一个空格,再打印错误信息。

#include <stdio.h>
#include <string.h>
#include <errno.h>
int main()
{
    FILE* pFile;
    //打开文件
    pFile = fopen("unexist.ent", "r");//“r”以读文件的形式打开文件,如果这个文件不存在就打开失败,打开失败会返回一个空指针
    if (pFile == NULL) {
        perror("打开文件失败,原因是");
        return 1;
    }
    else {
        printf("打开文件成功\n");
        fclose(pFile);
        pFile = NULL;
    }
    return 0;
}

打印:

打开文件失败,原因是: No such file or directory

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1809631.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【MySQL】聊聊唯一索引是如何加锁的

首先我们要明确&#xff0c;加锁的对象是索引&#xff0c;加锁的基本单位是next-key lock&#xff0c;由记录锁和间隙锁组成。next-key是前开后闭区间&#xff0c;间隙锁是前开后开区间。根据不同的查询条件next-key 可能会退化成记录锁或间隙锁。 在能使用记录锁或者间隙锁就…

认识Spring中的BeanFactoryPostProcessor

先看下AI的介绍 在Spring 5.3.x中&#xff0c;BeanFactoryPostProcessor是一个重要的接口&#xff0c;用于在Spring IoC容器实例化任何bean之前&#xff0c;读取bean的定义&#xff08;配置元数据&#xff09;&#xff0c;并可能对其进行修改。以下是关于BeanFactoryPostProce…

31-捕获异常(NoSuchElementException)

在定位元素的时候&#xff0c;经常会遇到各种异常&#xff0c;遇到异常又该如何处理呢&#xff1f;本篇通过学习selenium的exceptions模块&#xff0c;了解异常发生的原因。 一、发生异常 打开百度搜索首页&#xff0c;定位搜索框&#xff0c;此元素id"kw"。为了故意…

定个小目标之刷LeetCode热题(15)

这道题直接就采用两数相加的规则&#xff0c;维护一个进阶值&#xff08;n&#xff09;即可&#xff0c;代码如下 class Solution {public ListNode addTwoNumbers(ListNode l1, ListNode l2) {// 新建一个值为0的头结点ListNode newHead new ListNode(0);// 创建几个指针用于…

央视频官方出品,AI高考智友助你成就高考梦想

大家好&#xff0c;我是小麦。今天分享一款由央视频官方出品的AI工具套件&#xff0c;不仅支持直接使用&#xff0c;同时还具备了开发能力&#xff0c;是一款非常不错的AI产品工具&#xff0c;该软件的名称叫做扣子。 扣子是新一代 AI 应用开发平台。无论你是否有编程基础&…

Python图像处理入门学习——基于霍夫变换的车道线和路沿检测

文章目录 前言一、实验内容与方法二、视频的导入、拆分、合成2.1 视频时长读取2.2 视频的拆分2.3 视频的合成 三、路沿检测3.1 路沿检测算法整体框架3.2 尝试3.3 图像处理->边缘检测(原理)3.4 Canny算子边缘检测(原理)3.5 Canny算子边缘检测(实现)3.5.1 高斯滤波3.5.2 图像转…

网络学习(二)DNS域名解析原理、DNS记录

目录 一、为什么要使用DNS&#xff1f;二、因特网的域名结构三、DNS域名解析原理【含详细图解】四、DNS记录&#xff08;A记录、AAAA记录、CNAME记录等&#xff09; 一、为什么要使用DNS&#xff1f; 我们知道&#xff0c;TCP/IP 协议中是使用 IP 地址和端口号来确定网络上的某…

Unity 设置默认字体(支持老版及新版TMP)

普通UI-Text设置 &#xff08;同一unity版本设置一次即可&#xff09; 1.首先工程的Resources目录下创建Fonts文件夹用于存放字体 如下图所示 2.找到Unity的安装目录下的Editor\Data\Resources\PackageManager\BuiltInPackages\com.unity.ugui\Runtime\UI\Core\Text.cs文件 …

msfconsole利用Windows server2008cve-2019-0708漏洞入侵

一、环境搭建 Windows系列cve-2019-0708漏洞存在于Windows系统的Remote Desktop Services&#xff08;远程桌面服务&#xff09;&#xff08;端口3389&#xff09;中&#xff0c;未经身份验证的攻击者可以通过发送特殊构造的数据包触发漏洞&#xff0c;可能导致远程无需用户验…

C语言之main函数的返回值(在linux中执行shell脚本并且获取返回值)

一&#xff1a;函数为什么要返回值 &#xff08;1&#xff09;函数 在设计的时候是设计了参数和返回值&#xff0c;参数是函数的输入&#xff0c;返回值是函数的输出 &#xff08;2&#xff09;因为函数需要对外输出数据&#xff08;实际上是函数运行的一些结果值&#xff09;…

「51媒体」江苏媒体宣传报道,邀请媒体报道资源汇总

传媒如春雨&#xff0c;润物细无声&#xff0c;大家好&#xff0c;我是51媒体网胡老师。 江苏作为中国东部的重要省份&#xff0c;拥有丰富的媒体资源&#xff0c;包括电视台、广播电台、报纸以及网络媒体。 电视台 江苏卫视&#xff1a;作为江苏省唯一的省级卫视台&#xff…

支持YUV和RGB格式两路视频同时播放

1.头文件&#xff1a; sdlqtrgb.h #pragma once #include <QtWidgets/QWidget> #include "ui_sdlqtrgb.h" #include <thread> class SdlQtRGB : public QWidget {Q_OBJECTpublic:SdlQtRGB(QWidget* parent Q_NULLPTR);~SdlQtRGB(){is_exit_ true;//等…

ruoyi vue 集成积木报表真实记录

按官方文档集成即可 积木报表官方集成文档 集成问题 1.注意 idea 配置的 maven 需要设置成 本地配置&#xff0c;不可以使用 idea 自带的 maven,自带 maven 会导致私有源调用不到 后端代码 新建 base 模块 maven配置 <project xmlns"http://maven.apache.org/POM/…

33-unittest数据驱动(ddt)

所谓数据驱动&#xff0c;是指利用不同的测试数据来测试相同的场景。为了提高代码的重用性&#xff0c;增加代码效率而采用一种代码编写的方法&#xff0c;叫数据驱动&#xff0c;也就是参数化。达到测试数据和测试业务相分离的效果。 比如登录这个功能&#xff0c;操…

Linux shell编程学习笔记58:cat /proc/mem 获取系统内存信息

0 前言 在开展系统安全检查的过程中&#xff0c;除了收集cpu信息&#xff0c;我们还需要收集内存信息。在Linux中&#xff0c;获取内存信息的命令很多&#xff0c;这里我们着重研究 cat /proc/mem命令。 1 cat /proc/mem命令 /proc/meminfo 文件提供了有关系统内存的使用情况…

**《Linux/Unix系统编程手册》读书笔记24章**

D 24章 进程的创建 425 24.1 fork()、exit()、wait()以及execve()的简介 425 . 系统调用fork()允许父进程创建子进程 . 库函数exit(status)终止进程&#xff0c;将进程占用的所有资源归还内核&#xff0c;交其进行再次分配。库函数exit()位于系统调用_exit()之上。在调用fo…

开发小Tips:切换淘宝,腾讯,官方,yarn,cnpm镜像源,nrm包管理工具的具体使用方式(方便切换镜像源)

由于开发中经常要下载一些软件或者依赖&#xff0c;且大多数的官方源的服务器都在国外&#xff0c;网速比较慢&#xff0c;国内为了方便&#xff0c;国内一些大厂就建立一些镜像&#xff0c;加快下载速度。 1.各大镜像源的切换&#xff1a; 切换淘宝镜像源&#xff1a; npm …

基于51单片机的MQ-2烟雾报警设计

随着现代家庭用火、用电量的增加,家庭烟雾发生的频率越来越高。烟雾报警器也随之被广泛应用于各种场合。本课题所研究的无线多功能烟雾报警器采用STC89C51为核心控制器,利用气体传感器MQ-2、ADC0832模数转换器、DS18B20温度传感器等实现基本功能。通过这些传感器和芯片,当环…

圆 高级题目

上边的文章发了圆的初级题目&#xff0c;这篇来发高级 参考答案&#xff1a;ACCBBBBCDC

嵌入式作业6

1、利用SysTick定时器编写倒计时程序&#xff0c;如初始设置为2分30秒&#xff0c;每秒在屏幕上输出一次时间&#xff0c;倒计时为0后&#xff0c;红灯亮&#xff0c;停止屏幕输出&#xff0c;并关闭SysTick定时器的中断。 2、利用RTC显示日期&#xff08;年月日、时分秒&…