C语言中那些“不受限制”的字符串函数

“不受限制的“字符串函数

按《C和指针》中所说,那些常用的字符串函数都是“不是限制的”,就是说它们只能通过寻找字符串末尾的NULL来判断字符串的长度。

strlen

strlen函数用于求解字符串长度,其返回类型为unsigned int(即size_t)。strlen函数从起点开始,往后计数,遇到‘\0’停止。
值得注意的是:strlen函数的返回类型。看如下代码:

#include<string.h>
#include<iostream>
using namespace std;

int main()
{
    
    
	if ((strlen("abc") - strlen("abcdef")) > 0)
		cout << "大于" << endl;
	else
		cout << "小于" << endl;

	return 0;
}

输出 : 大于。不必惊奇,函数的size_t(-3)是一个正数。

strcpy

strcpy函数是字符串拷贝函数
函数原型为:
在这里插入图片描述
需要注意:目标字符串是要可以更改的,空间要大,足够存放拷贝的源字符串。
拷贝过程中,函数将源字符串的‘\0’一起拷贝到目标中。

#include<string>
#include<iostream>
using namespace std;
int main()
{
    
    
	char arr[20] = "abcdefgh******";
	char* p = "hello world";
	strcpy(arr, p);
	cout << arr << endl;
	return 0;
}

strcmp

strcmp函数为字符串比较函数。比较的不是字符串的长度,而是对应字符的ASCII值。
返回类型为:
在这里插入图片描述

#include<string>
#include<iostream>
using namespace std;
int main()
{
    
    
	char arr[] = "abcde";
	char p[] = "abde";
	cout << strcmp(arr,p) << endl;

	return 0;
}

strcat

strcat函数为字符串追加函数。函数原型:
在这里插入图片描述
将源字符串追加到目标字符串上。

int main()
{
    
    
	char arr[20] = "abcde ";
	char p[] = "hello";
	cout << strcat(arr, p) << endl;

	return 0;
}

strstr

strstr为字符串查找函数。函数原型为:
在这里插入图片描述
在目标字符串中查找子字符串,找的则返回指向子字符串的指针,否则返回空指针。

int main()
{
    
    
	char arr[] = "hello, how are you ?";
	char p[] = "are";
	cout << strstr(arr, p) << endl;

	return 0;
}

结果为:are you ?

strtok

strtok函数为字符串分隔函数。函数原型为:
在这里插入图片描述
strDelimit为字符串,定义了分隔字符的集合。函数执行是遇到分割字符时,将它改为‘\0’,范围一个指向这个标记的指针。注意:strtok函数执行时修改了字符串的内容。

int main()
{
    
    
	char str[] = "hello,how are you ?";
	char * p;
	p = strtok(str, ",?");
	while (p != NULL)
	{
    
    
		printf("%s\n", p);
		p = strtok(NULL, ",?");
	}
	return 0;
}

strerror

strerror函数的作用:返回错误码对应的信息。函数原型为
在这里插入图片描述
使用时要包含#include<errno.h>

小结

这些“不受限制的”的字符串函数,在执行过程中,函数本身要寻找字符串结尾的’\0’来作为结束执行标志。如果找不到’\0’,这函数执行可能就会越界,得不到正确的结果。

猜你喜欢

转载自blog.csdn.net/weixin_50941322/article/details/114274350
今日推荐