C语言进阶 之 字符函数和字符串函数

本文主要重点介绍处理字符和字符串的库函数的使用和注意事项

~求字符串长度
strlen
~长度不受限制的字符串函数
strcpy
strcat
strcmp
~长度受限制的字符串函数介绍
strncpy
strncat
strncmp
~字符串查找
strstr
strtok
~错误信息报告
strerror
~字符操作
~内存操作函数
memcpy
memmove
memset
memcmp

目录

1.前言

2.函数介绍

2.1 strlen 

2.2 strcpy

2.3 strcat

2.4 strcmp

2.5 strncpy

2.6 strncat

2.7 strncmp

2.8 strstr

2.9 strtok 

2.10 strerror 

2.11 memcpy

2.12 memmove

2.13 memcmp


1.前言

C语言中对字符和字符串的处理很是频繁,但是C语言本身是没有字符串类型的,字符串通常放在
常量字符串 中或者 字符数组 中。
字符串常量 适用于那些对它不做修改的字符串函数.
 

2.函数介绍

2.1 strlen 

size_t strlen ( const char * str ); 

 ! 字符串已经 '\0' 作为结束标志,strlen函数返回的是在字符串中 '\0' 前面出现的字符个数(不包
'\0' )

 ! 参数指向的字符串必须要以 '\0' 结束。
 ! 注意函数的返回值为size_t,是无符号的( 易错
 ! 学会strlen函数的模拟实现

为何函数返回值为size_t易错?请看如下代码:

#include <stdio.h>
#include <string.h>
int main()
{
    const char*str1 = "abcdef";
    const char*str2 = "bbb";
    if(strlen(str2)-strlen(str1)>0)
    {
        printf("str2>str1\n");
    }
    else
    {
        printf("srt1>str2\n");
    }
        return 0;
}

 代码结果如下:

这里是不是就有小伙伴认为str1 > str2才对?这里就要重新提及strlen这个函数的返回值size_t了,这个是无符号整型,当两个无符号整型相减,得到的结果也会是无符号整型,于是3 - 6得到的结果就被系统看成是无符号数,所以得到的结果是3 - 6 > 0

2.2 strcpy

char * strcpy ( char * destination, const char * source );

  Copies the C string pointed by source into the array pointed by destination, including the
  terminating null character (and stopping at that point).

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

博主总结就两个字 “替换”。源代码会把目标代码的数据替换掉,代码如下:

#include <stdio.h>
#include <string.h>
int main()
{
	char arr1[1000] = { "abcdefg" };
	char arr2[] = { "cccc" };
	strcpy(arr1, arr2);
	printf("%s" , arr1);
	return 0;
}

由于源字符串的 ’\0‘ 也会拷过去,所以当你打印目标字符串的时候,cccc把abcd给替换了,但是'\0'也拷进去了,于是打印便中止在这,后续的e f g还在目标字符串中。

源字符串必须以 '\0' 结束。
会将源字符串中的 '\0' 拷贝到目标空间。
目标空间必须足够大,以确保能存放源字符串。
目标空间必须可变。
学会模拟实现

2.3 strcat

 char * strcat ( char * destination, const char * source );

 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 destination被源的第一个字符覆盖,并且包含一个空字符在由目的地中的两个串接形成的新字符串的末尾。

博主总结就两个字 “追尾”,源字符串会添加到目标字符串的后面,代码如下:

#include <stdio.h>
#include <string.h>
int main()
{
	char arr1[1000] = { "abcdefg" };
	char arr2[] = { "cccc" };
	strcat(arr1, arr2);
	printf("%s" , arr1);
	return 0;
}

源字符串必须以 '\0' 结束。
目标空间必须有足够的大,能容纳下源字符串的内容。
目标空间必须可修改。
字符串自己给自己追加,如何?

如图,自己给自己追加也是可以的,但是要保证目标空间足够大!!!

2.4 strcmp

 int strcmp ( const char * str1, const char * str2 );

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字符。

博主总结“比大小”,这个函数用于比较两个字符串对应位置字符的大小ASCII码值),代码如下:

#include <stdio.h>
#include <string.h>
int main()
{
	char arr1[1000] = { "abcdefg" };
	char arr2[] = { "cccc" };
	int ret = strcmp(arr1, arr2);
	printf("%d" , ret);
	return 0;
}

标准规定:
第一个字符串大于第二个字符串,则返回大于0的数字
第一个字符串等于第二个字符串,则返回0
第一个字符串小于第二个字符串,则返回小于0的数字

2.5 strncpy

char * strncpy ( char * destination, const char * source, size_t num );
 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个字符复制到目标。如果源C字符串的末尾(由空字符发信号通知在复制num个字符之前被找到,目的地用零填充,直到总共写入了num个字符。

大家觉不觉得这个函数有点眼熟?他跟上文的2.2strcpy是不是很像?只是strncpy中间多了个n,这个函数跟strcpy的区别,只是末尾多了个参数size_t num,用法跟上文的strcpy没太大区别,只是可以让程序员调节 操作字符个数。代码如下:

#include <stdio.h>
#include <string.h>
int main()
{
	char arr1[1000] = { "abcdefg" };
	char arr2[] = { "cccc" };
	char* pf = strncpy(arr1, arr2, 3);
	printf("%s" , pf);
	return 0;
}


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

2.6 strncat

 char * strncat ( char * destination, const char * source, size_t num );

 ~Appends the first num characters of source to destination, plus a terminating null-character.
~If the length of the C string in source is less than num, only the content up to the terminating
null-character is copied.

将源的前num个字符追加到目标,再加上一个终止的null字符。如果源中的C字符串的长度小于num,则只有终止之前的内容空字符被复制。

 跟上文2.3strcat差别不大,一样只是多了个参数size_t num,代码如下:

int main()
{
	char arr1[1000] = { "abcdefg" };
	char arr2[] = { "cccc" };
	char* pf = strncat(arr1, arr2, 2);
	printf("%s" , pf);
	return 0;
}

2.7 strncmp

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

2.4 strcmp很像吧?直接上代码:

int main()
{
	char arr1[1000] = { "abcdefg" };
	char arr2[] = { "cccc" };
	int ret = strncmp(arr1, arr2, 2);
	printf("%d" , ret);
	return 0;
}

2.8 strstr

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

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

返回一个指向str1中第一个出现的str2的指针,如果str2不是str1的一部分,则返回一个空指针。

 这个函数就是在字符串中找字符串。在str1中找str2第一次出现的位置,然后返回一个指向该位置的指针,如果没有,那就返回NULL。看代码:

/* strstr example */
#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);
    puts (str);
    return 0;
}

2.9 strtok 

char * strtok ( char * str, const char * sep )

这个函数用于字符串的切割 

sep参数是个字符串,定义了用作分隔符的字符集合第一个参数指定一个字符串,它包含了0个或者多个由sep字符串中一个或者多个分隔符分割的标
记。
 strtok函数找到str中的下一个标记,并将其用 \0 结尾,返回一个指向这个标记的指针。(注:
strtok函数会改变被操作的字符串,所以在使用strtok函数切分的字符串一般都是临时拷贝的内容
并且可修改。)
strtok函数的第一个参数不为 NULL ,函数将找到str中第一个标记,strtok函数将保存它在字符串
中的位置。
strtok函数的第一个参数为 NULL ,函数将在同一个字符串中被保存的位置开始,查找下一个标
记。
如果字符串中不存在更多的标记,则返回 NULL 指针

看代码:

/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
    char str[] ="- This, a sample string.";
    char * pch;
    printf ("Splitting string \"%s\" into tokens:\n",str);
    pch = strtok (str," ,.-");
    while (pch != NULL)
    {
        printf ("%s\n",pch);
        pch = strtok (NULL, " ,.-");
    }
    return 0;
}

 

#include <stdio.h>
int main()
{
    char *p = "[email protected]";
    const char* sep = ".@";
    char arr[30];
    char *str = NULL;
    strcpy(arr, p);//将数据拷贝一份,处理arr数组的内容
    for(str=strtok(arr, sep); str != NULL; str=strtok(NULL, sep))
    {
        printf("%s\n", str);
    }
}

 

2.10 strerror 

 char * strerror ( int errnum );

返回错误码,所对应的错误信息。
 这个函数会将错误码翻译成错误信息。

代码如下:

/* strerror example : error list */
#include <stdio.h>
#include <string.h>
#include <errno.h>//必须包含的头文件
int main ()
{
    FILE * pFile;
    pFile = fopen ("unexist.ent","r");
    if (pFile == NULL)
    printf ("Error opening file unexist.ent: %s\n",strerror(errno));
    //errno: Last error number
    return 0;
}

 在C语言中使用库函数时,如发生错误,就会将错误码放在errno的变量中,errno是一个全局的变量,可直接用。

perror直接打印错误码所对应的错误信息,打印规则为:先打印自定义信息:xxx

如:perror("打印错误信息")。perror相当于printf + strerror

2.11 memcpy

void * memcpy ( void * destination, const void * source, size_t num );
 !函数memcpy从source的位置开始向后复制num个字节的数据到destination的内存位置。
 !这个函数在遇到 '\0' 的时候并不会停下来。
 !如果source和destination有任何的重叠,复制的结果都是未定义的。

代码如下:

/* memcpy example */
#include <stdio.h>
#include <string.h>
struct {
    char name[40];
    int age;
} person, person_copy;
int main ()
{
    char myname[] = "Pierre de Fermat";
    /* using memcpy to copy string: */
    memcpy ( person.name, myname, strlen(myname)+1 );
    person.age = 46;
    /* using memcpy to copy structure: */
    memcpy ( &person_copy, &person, sizeof(person) );
    printf ("person_copy: %s, %d \n", person_copy.name, person_copy.age );
    return 0;
}

2.12 memmove

 void * memmove ( void * destination, const void * source, size_t num );

和memcpy的差别就是memmove函数处理的源内存块和目标内存块是可以重叠的。
如果源空间和目标空间出现重叠,就得使用memmove函数处理。

/* memmove example */
#include <stdio.h>
#include <string.h>
int main ()
{
    char str[] = "memmove can be very useful......";
    memmove (str+20,str+15,11);
    puts (str);
    return 0;
}

2.13 memcmp

int memcmp ( const void * ptr1  ,  const void * ptr2  ,  size_t num );

比较从ptr1和ptr2指针开始的num个字节
返回值如下:

 

/* memcmp example */
#include <stdio.h>
#include <string.h>
int main ()
{
    char buffer1[] = "DWgaOtP12df0";
    char buffer2[] = "DWGAOTP12DF0";
    int n;
    n=memcmp ( buffer1, buffer2, sizeof(buffer1) );
    if (n>0) printf ("'%s' is greater than '%s'.\n",buffer1,buffer2);
    else if (n<0) printf ("'%s' is less than '%s'.\n",buffer1,buffer2);
    else printf ("'%s' is the same as '%s'.\n",buffer1,buffer2);
    return 0;
}

库函数的模拟实现将在下篇博客发布,感谢阅读。 

猜你喜欢

转载自blog.csdn.net/A1546553960/article/details/133957630
今日推荐