C语言中字符串处理函数

头文件:string.h

/*字符串处理函数,string.h

	1.puts(数组名):将字符串数组中的字符串输出到显示器。
	char c[]="base\nsdefa";
	puts(c);//==printf("%s",c);


	2.gets(数组名):输入字符串。
	char st[15];
	gets(st);//==scanf("%s",st);
	//之间区别:gets函数并不以空格作为字符串输入结束的标志,而只以回车作为输入结束。而scanf不同
	puts(st);
	
	3.stract(arry1,arry2);//将数组2中的字符串连接到字符数组1中字符串的后面,并删除字符串1后的串标志"\0";函数返回值为字符数组1的首地址

	static char st1[30]="my name is";
		char st2[10];
		gets(st2);
		//char *p=strcat(st1,st2);
		//puts(p);
		//等价
		strcat(st1,st2);
		puts(st1);

	4.字符串拷贝函数strcpy

	格式:strcpy(st1,st2);将字符数组2中的字符串拷贝到字符数组1中,"\0"也一起拷贝。字符数组2可以是字符串常量,相当于把一个字符串赋予一个字符数组。
	st1需要有足够的长度。
	
	char st1[15],st2[]="C Language";
	strcpy(st1,st2);
	puts(st1);

	5.字符串比较函数strcmp
	strcmp(st1,st2);//按ASCII码顺序比较两个数组中的字符,并返回比较结果。比较两个字符串常量,比较数组和字符串常量。
	str1=str2,返回值= 0;
	str1>str1,返回值>0;
	str1<str2,返回值<0;


	int k;
	static char st1[15],st2[]="C Language";
	gets(st1);
	k=strcmp(st1,st2);
	if(k==0) printf("st1=st2\n");
	else if(k>0) printf("st1>st2\n");
	else printf("st1<st2\n");

	6.strlen 测字符串长度strlen
	格式:strlen(字符数组名)
	功能:测字符串的实际长度(不含字符串结束标志'\0')并作为函数返回值。

	char st1[]="C language";
		int k=strlen(st1);
		printf("%d",k);

相关练习:
1.把一个整数按大小顺序插入已排好序的数组中。

#include<stdio.h>

int main()
{
	int a[11]={127,3,6,28,54,68,87,105,162,18},f=50,i=0;
	//可以采用任意的排序算法
	for(int i=0;i<10;i++){
		for(int j=0;j<9-i;j++){
			if(a[j]>a[j+1]){
				int temp;
				temp = a[j];
				a[j] = a[j+1];
				a[j+1] = temp;
			}
		}
	
	}
	/*
	for(int i=0;i<10;i++){
		printf("%d ",a[i]);
	}

	*/
	for(i=0;i<10;i++){//找到比f大的点的位置,即为插入的地方
		if(f<a[i]) break;//跳出循环。主要i必须定位全局的标量,才能得到插入的位置点
	}

	for(int j=9;j>=i;j--){//从后开始遍历,知道插入点处,范围内所有的点都向右移动一位。
		a[j+1] = a[j];
	}
	a[i]=f;//将f插入到该位置
	for(i=0;i<11;i++){
		printf("%d ",a[i]);
	}
}

2.在二维数组arr中选出各行最大的元素组成一个一维数组result;

#include<stdio.h>


int main()
{
	int arr[][4]={3,16,87,65,4,32,11,108,10,25,12,37};
	int result[3],max;
	for(int i=0;i<3;i++){
		max=arr[i][0];
		for(int j=1;j<4;j++){
				if(max<arr[i][j]){
					int temp;
					temp=max;
					max=arr[i][j];
					arr[i][j]=temp;
				}
			}
		result[i]=max;
	}
	for(int i=0;i<3;i++){
		printf("%d ",result[i]);
	}	
	return 0;
}

3.输入5个国家的名称按字母顺序排列输出

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

int main()
{
	char cs[5][20],st[20];
	for(int i=0;i<5;i++)
		gets(cs[i]);//每一个字符数组表示一个国家名称
	for(int i=0;i<5;i++){
		for(int j=0;j<4-i;j++){
				if(strcmp(cs[j],cs[j+1])>0){//前面的小于后面
					char temp[20];
					strcpy(temp,cs[j]);
					strcpy(cs[j],cs[j+1]);
					strcpy(cs[j+1],temp);
				}
			}
	}
		
	for(int i=0;i<5;i++){
		printf("%s ",cs[i]);
	}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值