10.2 全局变量、局部变量、静态变量(strtok的用法以及实现原理)

全局变量定义在所有函数外面,所有函数都可以调用全局变量。但是局部变量只能在定义它的函数中使用,不能用在其他函数中。

#include<iostream>
using namespace std;
void Func()
{
	static int n = 4;//静态变量只初始化一次,下次调用的时候不会再次初始化,会直接跳过这个语句 
	cout << n << endl;
	++ n;
} 
int main()
{
	Func();//第一次调用,n=4,++n后n=5 
	Func();//跳过n=4,n不再初始化,n=5, ++n后n=6 
	Func();//跳过n=4,n不再初始化,n=6,++n后n=7 
	return 0;
}

#include<iostream>
using namespace std;

void Func()
{
	int n = 4;//不管之前的n为多少,n会一直初始化为4 
	cout << n << endl;//4
	++ n;
} 

int main()
{
	Func();//n会一直初始化为4,所以输出的结果一直都为4 
	Func();
	Func();
	return 0;
} 

strtok:将字符串分隔为单词的函数。

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
	char str[] = "- This, a sample string, Ok.";
	char *p = strtok(str," -,.");
	while(p != NULL)
	{
		cout << p << endl;
		p = strtok(NULL, " -,.");
	}
	return 0;
} 

实现原理:

#include<iostream>
#include<cstring>
using namespace std;

char *Strtok(char *p, char *sep)
{
	static char *start;
	if(p)
		start = p;
	for(; *start && strchr(sep, *start); ++ start);
	if(*start == 0)
		return NULL;
	char * q =  start;
	for(; *start && !strchr(sep, *start); ++ start);
	if(*start)
	{
		*start = 0;
		++ start;
	 } 
	 return q;
}
int main()
{
	char str[] = "- This, a sample string, Ok.";
	char *p = Strtok(str," -,.");
	while(p != NULL)
	{
		cout << p << endl;
		p = Strtok(NULL, " -,.");
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/yanyanwenmeng/article/details/81879718