【C语言】第九天笔记总结

字符串

1、字符串的表示

A、C语言里面字符串只能用字符数组来存储

B、字符串要求这个数组必须至少有一个\0字符,所以字符串开空间时必须要比数组中的元素多一个空间来存储\0

2、字符串的专用格式控制符 %s

输入:%s需要字符串的某个字符地址,从给定的地址开始接收字符放入char型空间中,直到遇到空格或者回车结束输入。

输出:%s需要字符串的某个字符地址,从给定的地址开始读char型字符并输出,直到读到\0字符结束输出

3、多个字符串

A、在需要存储多个字符串时,就需要用到char型的二维数组

B、无论是输入还是输出在使用%s控制符时,二维数组只需改变行数,就可以写入或者访问整个二维数组

4、字符串的库函数

4.1、在使用库函数时需要引入库函数的头文件

4.2、函数声明要清楚,因为函数的形式决定怎么使用函数

4.3、常用的字符串处理函数:

A、atof ---- 将字符串转成浮点型数据

头文件#include <stdlib.h>

函数声明double atof( const char *str );

例:

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

int main(void)
{
    char str[30]="34.653absd";
    double res;
    res = atof(str);
			
    printf("%lf",res);
    return 0;
}
	

注:atof处理的字符串必须要数字开头,直到遇到非数字字符结束;

B、memset ---- 负责将某一段内存填充某一个字符

头文件:#include <string.h>

函数声明:void*memset(void*buffer,int ch,size_t count);

例:

#include <stdio.h>

int main(void)
{
    char phone[20] = "0755-888888";
    memset(&phone[2],'@',5);//从数组下标2开始填充5个@字符
		
	printf("%s",name);

	return 0;
}

C、strlen ---- 求字符串长度

头文件:#include <string.h>

函数声明:size_t strlen( char *str ); 

例:

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

int main(void)
{
    char str[20];
	printf("请输入字符串:");
	scanf("%s",str);
				
	int len;
	len = strlen(str); //从头开始计算字符串长度
	printf("%d\n",len);
				
	int len1;
	len1 = strlen(&str[2]); //从数组下标2开始计算字符串长度
	printf("%d\n",len1);
	return 0;
}			

sizeof与strlen的区别

sizeof:计算任意空间所占字节数

strlen:只能用于字符串,从给定的地址计数直到遇到到\0

D、strcat ---- 字符串拼接

头文件:#include <string.h>

函数声明:char *strcat( char *str1, const char *str2 );

例:

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

int main(void)
{
    char s1[30] = "hello";
	char s2[10] = "world";
			
	// 想把s2拼接到s1的后面			
	strcat(s1,s2); 
			
	printf("%s",s1);

	return 0;
}

E、strcpy --- 拷贝字符串

头文件:#include<string.h>

函数声明:char *strcpy( char *to, const char *from );

例:

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

int main(void)
{
	char s1[10] = "hello";		
	char s2[10] = "hihihhi";

	strcpy(s2,s1);
			
	printf("%s",s2);
			
	printf("%c",s2[6]);

	return 0;
}
  • 20
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值