C语言_字符串

1

1> 什么是字符串?

羊肉串,字符串,字符连起来,就是字符串:

形式:
"OK"'O', 'K', '\0'3个字符组成;
 
存储:
char a[20] = "OK";
char a[20] = {'O', 'K', '\0'};  

2> 自定义函数

2.1> gets

char *gets(char *str)
{
	char ch;
	int i = 0;
	ch = getchar();
	while (ch != '\n') {
		str[i] = ch;
		i++;
		ch = getchar();
	}
	str[i] = '\0';
	
	return str;
}

2.2> puts

int puts(char *str)
{
	int i = 0;
	while (str[i] != '\0' ) {
		putchar(str[i]);
		i++;
	}
	putchar('\0');

	return i;
}

2.3> strcpy

/**
 * strcpy - Copy a %NUL terminated string
 * @dest: Where to copy the string to
 * @src: Where to copy the string from
 */
char *strcpy(char *dest, const char *src)
{
	int i = 0;
	
	while (src[i] != '\0') {
		dest[i] = src[i];
		i++
	}
	
	dest[i] = '\0';
	
	return dest;
}

2.4> strcpy _linux

/**
 * strcpy - Copy a %NUL terminated string
 * @dest: Where to copy the string to
 * @src: Where to copy the string from
 */
char *strcpy(char *dest, const char *src)
{
	char *tmp = dest;

	while ((*dest++ = *src++) != '\0')
		/* nothing */;
	
	return tmp;
}

2.5> strcat

/**
 * strcat - Append one %NUL-terminated string to another
 * @dest: The string to be appended to
 * @src: The string to append to it
 */

char *strcat(char *dest, const char *src)
{
	int i = 0;
	int j = 0;
	while(dest[i] != '\0') {
		i++
	}
	while(src[j] != '\0') {
		dest[i+j] = src[j];
		j++;
	}
	dest[i+j] = '\0';
	
	return dest;
}

2.6> strcat _linux

/**
 * strcat - Append one %NUL-terminated string to another
 * @dest: The string to be appended to
 * @src: The string to append to it
 */

char *strcat(char *dest, const char *src)
{
	char *tmp = dest;

	while (*dest)
		dest++;
	while ((*dest++ = *src++) != '\0')
		;
	return tmp;
}

2.7> strcmp

/**
 * strcmp - Compare two strings
 * @cs: One string
 * @ct: Another string
 */

//CS: H O S T \0
//Ct: H O S T F \0
//
int strcmp(const char *cs, const char *ct)
{
	int i = 0;
	while(cs[i] != '\0') {
		if(cs[i] > ct[i]) {
			return 1;
		} else if(cs[i] == ct[i]) {
			i++
		} else {
			return -1;
		}
	}
	
	if(ct[i] != '\0') {
		return -1;
	} else {
		return 0;
	}	
}

2.8> strcmp _linux

/**
 * strcmp - Compare two strings
 * @cs: One string
 * @ct: Another string
 */
int strcmp(const char *cs, const char *ct)
{
	unsigned char c1, c2;

	while (1) {
		c1 = *cs++;
		c2 = *ct++;
		if (c1 != c2)
			return c1 < c2 ? -1 : 1;
		if (!c1)
			break;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值