c 字符串替换

#include <stdio.h>

/*
字符串替换
char *str_replace(char *dest, char *src, char *replace)
在目标字符串中(dest)查找原字符串(src),如果有找到则替换为replace所指向的字符串。
*/

int mystrlen(char *dest)								//字符长度
{
	int len=0;
	while(*dest++)
		len++;
	return len;
}

char * mystrchr(const char *dest, char search)			
{
	while(*dest != '\0')								//字符查找,字符串不为空字符时,进入循环
	{
		if (*dest == search)							//目标字符如果等于查找字符,则返回指针地址
		{
			return (char *)dest;
		}
		dest++;											//指针自加
	}
	return NULL;
}

int mystrcmp(const char *dest, const char *src)
{
	int result=0;
	while(*src != '\0')
	{
		result = *dest - *src;
		if (result != 0)
		{
			return result;
		}
		dest++;
		src++;
	}
	return result;
}

char * mystrcpy(char *dest, const char *src)
{
	char *start = dest;
	while(*src != '\0')
	{
		*dest = *src;
		dest++;
		src++;
	}
	return start;
}

char *strend(char *str)
{
	while(*str++)
		;
	str--;
	return str;
}

char *str_replace(char *dest, char *src, char *replace)
{
	int s_flag=1, len_src, len_replace, len_move, n;
	char *p, *start=dest, *end=strend(dest);
	p = mystrchr(dest, *src);

	// 找到相同处
	while(p != end)
	{
		if (p == NULL)
		{
			return NULL;
		}	
		if(mystrcmp(p, src) == 0)
		{// 找到字符串,结束循环
			s_flag = 0;
			break;
		}
		p = mystrchr(p+1, *src);
	}

	// 字符串未找到
	if (s_flag)
	{
		return NULL;
	}
	// 否则找到这个字符串了		

	/*
		移动原本的串
	*/
	// 改变这个串的结构,来适应新替换进来的字符串
	len_src = mystrlen(src);
	len_replace = mystrlen(replace);
	len_move = len_replace - len_src;
	start = p + len_src;

	n = mystrlen( start );

	// 根据len_move的正负来判断往前移动还是往后移动

	if (len_move > 0)
	{
		// 往后移动
		while(n >= 0)
		{
			*( end + len_move ) = *end;					//当目标字符串比替换字符串长时,令整个字符串向后移动字符串位置
			end--;
			n--;
		}
	}else
	{
		// 往前移动
		while(n >= 0)
		{
			*( start + len_move ) = *start;				//当目标字符串比替换字符串短时,令整个字符串向前移动字符串位置
			start++;
			n--;
		}
	}


	// 字符串已移动完毕
	// printf("%sn", dest);

	/*
		将替换字符串拷贝进来
	*/
	mystrcpy(p, replace);

	return dest;
}

int main()
{
	char text[50] = "hi, test is a this.";
	printf("原本的字符串:%sn", text);
	if(str_replace(text, "this", "bug") != NULL)
	{
		printf("字符串替换后:%sn", text);
	}
	else
	{
		printf("字符串替换错误n");
	}
}

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s