一.字符函数和字符串函数
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