字符串替换的程序,虽然有点幼稚,但是几乎没有抄袭的痕迹。

 这个程序有没有bug当然是不知道的,还是谨慎的看吧!

 

#include <stdio.h>

//求字符串长度
int _strlen(char* s) {
	int len = 0;
	while(*s++) {
		len++;
	}
	return len;
}

//比较两个字符串是否相同
int _strcmp(char* s0, char* s1) {
	int len0 = _strlen(s0), len1 = _strlen(s1);
	if(len0 != len1) {
		return 0;
	} else {
		len1 = 0;
		while((*s0) && (*s0++ == *s1++)) {
			len1++;
		}
		if(len0 == len1) {
			return 1;
		} else {
			return 0;
		}
	}
}

//字符串拷贝,尾部带结束符
void _strcpy(char* s0, char* s1, int len) {
	int i;
	for(i = 0; i < len; i++) {
		*s1++ = *s0++;
	}
	*s1 = '\0';
}

//字符串拷贝,尾部不带结束符
void __strcpy(char* s0, char* s1, int len) {
	int i;
	for(i = 0; i < len; i++) {
		*s1++ = *s0++;
	}
}


//向前或向后移动i位,目的是使间隙符合被替换字符串的长度
void _move_s(char* s, int i) {
	if(!i) {
		return;
	}
	if(i > 0) {
		while(*s) {
			*s = *(s + i);
			s++;
		}
		*s = '\0';
	} else {
		i = -i;
		char* t = s + _strlen(s) + i - 1;
		*(t + 1) = '\0';
		for(;  t >= s + i; t--) {
			*t= *(t - i);
		}
	}
}

//字符串替换
void _replace_s(char*s, char* s0, char* s1) {
	char str[0xff];
	if(_strcmp(s0, s1)) {
		return;
	} else {
		while(*s) {
			_strcpy(s, str, _strlen(s0));
			if(_strcmp(s0, str)) {
				_move_s(s, _strlen(s0) - _strlen(s1));
				__strcpy(s1, s, _strlen(s1));
				s += _strlen(s1);
			} else {
				s++;
			}
		}
	}
}

//主程序,测试用
int main(void) {
	char str[0xff] = "####Test!  Test## Test!    Te st!&&&&&";
	printf("%s\n", str);
	_replace_s(str, "Test", "GOODGOOD");
	printf("%s\n", str);
}

发布了159 篇原创文章 · 获赞 14 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_39410618/article/details/99698513