C语言基础 入门学习(六)

1.如何大小端转换

bool IsBig()
{
	int sh = 0x12345678;
	char*p = (char*)&sh;
	if (*p == 0x78)
	{
		return false;
	}
	return true;
}
int Tran(int n)
{
	return (((n & 0xff000000) >> 24) | ((n & 0x00ff0000) >> 8) | ((n & 0x0000ff00) << 8) | ((n & 0x000000ff) << 24));
}

2.字符串中按但词逆序

void Reverse(char*pbegin, char*pend)
{
	assert(pbegin != NULL&&pend != NULL);
	char tmp;
	while (pbegin < pend)
	{
		tmp = *pbegin;
		*pbegin++ = *pend;
		*pend-- = tmp;
	}
}
char*ReverseSentence(char*str)
{
	assert(str != NULL);
	char *pbegin = str;
	char *pend = str;
	while (*pend != '\0')
	{
		pend++;
	}
	Reverse(pbegin, --pend);
	pbegin = str;
	pend = str;
	
	while(*pbegin!='\0')
	{
		if (*pbegin == ' '|| *pbegin == '\0')
		{
			pbegin++;
			pend++;
		}
		else if (*pend == ' ')
		{
			Reverse(pbegin, --pend);
			pbegin = ++pend;
		}
		else
		{
			pend++;
		}
	}
		
	return str;
}

3.判断字符串为回文串

bool IsCstring(const char*str)
{
	assert(*str != NULL);//DEBUG
	if (str == NULL||str<=0)//release
	{
		return false;
	}
	const char*p = str;//指向串头
	const char*q = str+strlen(str)+1;//指向串尾
	
	while (p<q)
	{
		if (*p == *q)
		{
			p++;
			q--;
		}
		else
		{
			return false;
		}

	}
	return true;
}

4.二分查找法

int Binarserach(int *arr, int len,int key)
{
	int low = 0;
	int high = len - 1;
	while (low<=high)
	{
		int mid = (low + high) >> 1;
		if (arr[mid] > key)
		{
			high = mid - 1;
		}
		else if (arr[mid] < key)
		{
			low = mid + 1;
		}
		else if(arr[mid]==key)
		{
			return mid;
		}
	}
	return -1;

}

//一级指针:变量的地址
//二级指针:一级指针的地址
5.*const define的区别
const 定义常变量 具有变量的基本属性:有类型,占存储单元,只是不许改变其值。
define 定义符号常量 是预编译指令,只是用符号常量代表一个字符串,在预编译时
仅是进行字符替换,在预编译后,符号常量就不存在。

系统对符号常量的名字不分配存储单元,常变量占存储单元
6.求字符串单词的数量

int WordNum(char *str)
{
	int count = 0;
	char *p = str;
	char *q = str;
	assert(*str != NULL);
	while (*p != '\0')
	{
		if (*p == ' '|| *p == '\0')
		{
			p++;
			q++;
		}
		else if (*q == ' '|| *q == '\0')
		{
			count++;
			p = ++q;
		}
		else
		{
			q++;
		}
	}
	return count;
}

猜你喜欢

转载自blog.csdn.net/zhangfei5354/article/details/83375275