现在的位置: 首页 > 编程语言 > 正文

实现几个字符串常用函数

2019年01月10日 编程语言 ⁄ 共 1359字 ⁄ 字号 评论关闭

实现几个字符串常用函数,练习一下写代码。经常谢谢代码,使自己不要忘了如何写代码。

字符比较函数

字符串赋值函数

求字符串长度

字符串那倒置

字符串比较

字符串连接

 

// string.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <assert.h>
#include "string.h"

//字符交换函数
void charswap(char& ch1, char& ch2)
{
	char ch = ch1;
	ch1 = ch2;
	ch2 = ch;
}

//求字符串长度
int stringlength(const char* sourstr)
{
	const char *pstr = sourstr;
	int length = 0;
	while(*pstr++ != '\0')
	{
		length++;
	}
	return length;
}

//字符串那倒置
char* stringconvert(char* sourstr)
{
	int length = stringlength(sourstr);
	int loopnumber = length / 2;
	int index = 0;
	while(index < loopnumber)
	{
		charswap(*(sourstr + index), *(sourstr + length - index - 1));
		index++;
	}
	return sourstr;
}

//字符串复制
char* stringcopy(char* deststr, const char* sourstr)
{
	const char* pstr = sourstr;
	int index = 0;
	while(*pstr != '\0')
	{
		*(deststr + index) = *pstr++;
		index++;
	}
	*(deststr + index) = '\0';
	return deststr;
}

//字符串连接
char* stringcontact(char* deststr, const char* sourstr)
{
	const char* pstr = sourstr;
	int length = stringlength(deststr);
	int index = 0;
	while(*pstr != '\0')
	{
		*(deststr + length + index) = *pstr++;
		index++;
	}
	*(deststr + length + index ) = '\0';
	return deststr;
}

//字符串比较函数
int stringcompare(const char* deststr, const char* sourstr)
{
	const char* pdest = deststr;
	const char* psour = sourstr;

	while(*pdest == *psour && *pdest != '\0')
	{
		pdest++;
		psour++;
	}
	return *pdest - *psour;
}


int main(int argc, char* argv[])
{ 
	char buff1[100];
	char buff2[100];
	stringcopy(buff1, "reqre12345");
	stringcopy(buff2, "reqre1");

	printf("%d\n", stringcompare(buff1, buff2));

	getchar();

	return 0;
}

 

抱歉!评论已关闭.