第77节 字符和字符串处理函数

一.字符函数和字符串函数

1.C语言中进行文字处理的方法

①自编代码完成

②利用库函数

2.字符库函数

include <ctype.h>

3.串处理函数

include <string.h>

二.字符函数 include <ctype.h>

实例: 利用库函数统计数字字符个数

#include <stdio.h>
int main()
{
	char str[50] = { 0 };
	int i = 0, n = 0;
	printf("输入字符串: ");
	gets(str);
	while (str[i] != '\0')
	{
		if (isdigit(str[i])) n++;
		//等同于: str[i]>='0'&&str[i]<='9';
		i++;
	}
	printf("数字字符数:%d\n", n);
}

三.字符串函数 include<string.h>

1.字符串连接函数 strcat

 格式: char *strcat(char *str1, const char *str2);

 功能: 将字符串str2连接到str1的后面

 参数: str1,str2;

 返回: str1的地址。

#include <stdio.h>
int main()
{
	char str1[30] = "Good "; 
	/数组长度要确定,否则容易越界异常
	char str2[] = "morning";
	strcat(str1, str2);
	/功能:将str2连接到str1的后面(连接后放在str1中)
	printf("%s", str1);
}
运行结果:
Good morning

2.字符串复制函数strcpy

 格式: char *strcpy(char *str1, const char *str2);

 功能: 将str2复制到str1中去,并将str1中已有字符覆盖。

 参数: str1,str2;

 返回: str1的地址。

#include <stdio.h>
int main()
{
	char str1[30] = "Good "; 
	/数组长度要确定,否则容易越界异常
	char str2[] = "morning";
	strcpy(str1, str2); 
	/功能:将str2复制到str1中去,并将str1中已有字符覆盖
	printf("%s", str1);
}
运行结果:
morning

3.字符串比较函数strcmp

 格式: int strcmp(const char *str1, const char *str2);

 功能: 比较两个字符串大小;

 参数: str1,str2;

 返回: str1==str2,返回0; str1>str2,返回1; str1<str2返回-1;

 规则: 自左至右,逐个比较ASCII码值,直到出现不同的字符或遇到’\0’。

#include <stdio.h>
int main()
{
	char str1[] = "Good "; 
	char str2[] = "morning";
	printf("%d", strcmp(str1, str2));
}
运行结果:
-1

4.字符串长度函数strlen

 格式: size_t strlen(const char *str);

 功能: 计算字符串str的长度

 参数: str;

 返回: 字符串中的实际长度,不包括’\0’。

#include <stdio.h>
int main()
{
	char str[10] = "Good"; 
	printf("%d", strlen(str));
}
运行结果:
4
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值