常用字符串处理函数string

本文详细介绍了C语言中常用的字符串处理函数,包括strcat用于字符串连接,strcpy用于字符串复制,strcmp用于字符串比较,以及strlen用于计算字符串长度。此外,还提到了strupr和strlwr分别用于将字符串转换为大写和小写。这些函数在C语言编程中处理字符串时非常实用。
摘要由CSDN通过智能技术生成

目录

1.字符串连接函数strcat

2.字符串复制函数strcpy

3.字符串比较函数strcmp

4.测试字符长度函数strlen

 5.strupr和strwr函数


在使用字符串函数时须在程序前面使用string函数,如

#include<string.h>   //string---字符串,h(head)表示头文件

1.字符串连接函数strcat

其一般形式为

        strcat(字符数组名1,字符数组名2)

其功能是:把字符数组2中的字符串连接到字符数组1中的字符串后面,同时删去字符串1后面的结束标志符'\0'。

一般打印“hello world!”使用的是标准输入输出函数stdio

#include <stdio.h>

int main()
{
	printf("hello world!\n");
    return 0;
}

而当我们使用strcat函数时,代码模板如下:

#include <stdio.h>
#include <string>

int main()
{
	char str1[15] = "hello ",str2[] = "world!";
	strcat(str1, str2);    //将str2的内容加在了str1的后面
	printf("%s", str1);    //此时打印str1的结果就为 hello world!
	return 0;
}

2.字符串复制函数strcpy

一般格式为:

        strcpy(字符数组1,字符数组2)

其功能为:把字符数组2的内容复制给字符数组1中

例如

#include <stdio.h>
#include <string>

int main()
{
	char str1[] = "hello", str2[] = "world";
	strcpy(str1, str2);    //表示运行之后“str1”的内容变为“world”
	printf("%s", str1);    //此时显示的结果为world
    
    return 0;
}

3.字符串比较函数strcmp

一般形式为:

        strcmp(字符数组名1,字符数组名2)

其功能是按照ASCII码顺序比较两个数组的字符串,并由函数返回值返回比较结果。

        字符串1=字符串2,返回值为0;

        字符串1>字符串2,返回值为正数;

        字符串1<字符串2,返回值为负数;

同时改函数也可以比较两个字符常量或比较数组和字符常量。

例如,比较下列两个数组的字符串

#include <stdio.h>
#include <string>

int main()
{
	int a;
	char str1[15] = "hello ",str2[] = "world!";
	a=strcmp(str1, str2);
	if (a > 0)
		printf("str1>str2\n");
	else
		printf("str1<str2\n");
	//a==o同样的道理,这里就不作代码演示了
	return 0;
}

输出结果为:str1<str2

4.测试字符长度函数strlen

一般形式:

        strlen(字符数组名) 

功能是测试字符串的实际长度(注意不含字符串结束符'\0','\0'不算作字符串的内容)并作为函数值返回

例如下面代码,这样便可以知道str中的字符串长度。

#include <stdio.h>
#include <string>

int main()
{
	int k;
	char str[] = "NICE";
	k = strlen(str);
	printf("%d", k);    //k的结果为4
}

 5.strupr和strwr函数

一般格式为:

        strupr(字符数组名);

作用为将字符串转换为大写形式,不改变其他字符

        

一般格式为:

        strlwr(字符数组名);

功能为将字符串转换为小写形式,不改变其他字符

例如

#include <stdio.h>
#include <string>

int main()
{
	
	char str1[] = "nice!", str2[] = "GOOD!!";
	_strupr(str1);//转化为大写
	_strlwr(str2);//转化为小写
	printf("%s\n", str1);
	printf("%s\n", str2);
}

输出结果为

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值