当前位置:网站首页>C语言实验八 字符数组程序设计
C语言实验八 字符数组程序设计
2022-08-02 00:18:00 【Meteor.792】
一、实验目的
(一)掌握字符数组的定义、初始化和应用;
(二)掌握字符串处理函数的使用。
二、预习要求
重点预习的内容:C语言中字符串的存储表示;字符数组输入输出的方法;常用的字符串处理函数的使用。
三、实验内容
(一)输入下面的程序并运行,观察程序运行的结果,并分析原因(注意程序第2行中有些单引号之间是空格)。
/* c8-1.c 字符数组的输出*/
#include "stdio.h"
void main( )
{ char a[10]={ ’I’, ’ ’, ’a’, ’m’, ’ ’, ’a’, ’ ’, ’b’, ’o’, ’y’};
printf("%s\n",a);
}
将字符数组a的大小改为11,再运行程序,并将结果与修改前的结果进行比较,分析原因。
(二)下面程序的功能是实现将两个字符串连接起来并输出结果,注意不使用strcat函数。
编程提示:
1.定义两个一维字符型数组str1、str2和两个循环变量。
2.为两个字符数组输入两个字符串(可使用scanf函数或gets函数整体赋值,要注意scanf和gets函数的区别,在对字符串赋值时,scanf函数不能出现空格)。
3.确定字符数组str1结束的位置。
4.再将字符数组str2中的内容连接到字符数组str1的后面。
5.为字符数组str1赋字符串结束的标志’\0’。
6.输出连接后的字符数组str1。
/* c8-3.c 字符串连接*/
#include "stdio.h"
void main( )
{ char str1[100],str2[100];
int i=0,j=0;
printf("please input the string1:");
scanf("%s",str1);
printf("please input the string2:");
gets(str2);
for(i=0; str1[i]!='\0'; i++) ; /*注意,此处空语句不可少*/
for(j=0;str2[j]!='\0';j++)
{ str1[i]=str2[j];
i++;
}
str2[i]='\0'; /*给出新的字符串的结束符*/
printf("the catenated string is %s",str1);
}
(三)下面程序的功能是用strcat函数实现将字符串2连接到字符串1的后面并输出。
/* c8-4.c 字符串连接*/
#include "stdio.h"
#include "string.h"
void main( )
{ char str1[80]="This Is a ",str2[80]="c Program";
printf("String1 is: %s\n",str1);
printf("String2 is: %s\n",str2);
strcat(str1,str2); /*使用strcat函数实现*/
printf("Result is: %s\n",str1);
}
(四)下面程序的功能是实现将一个字符串中的所有大写字母转换为小写字母并输出。
例如:当字符串为"This Is a c Program"
输出:"this is a c program"
/* c8-5.c 字符串中的大写字母转为小写字母*/
#include "stdio.h"
void main( )
{ char str[80]="This Is a c Program";
int i;
printf("String is: %s\n", str);
for(i=0; str[i]!='\0'; i++)
if (str[i]>='A' && str[i]<='Z')
str[i]=str[i]+32; /*将大写字母转换成小写字母*/
printf("Result is: %s\n",str);
}
思考:如果将字符串中的所有小写字母转换为大写字母,又将如何修改程序?
四、实验注意事项
(一)注意C语言中字符串是作为一维数组存放在内存中的,并且系统对字符串常量自动加上一个‘\0’作为结束符,所以在定义一个字符数组并初始化时要注意数组的长度。
(二)注意用scanf函数对字符数组整体赋值的形式。
边栏推荐
- 微信支付软件架构,这也太牛逼了!
- 思维导图,UML在线画图工具
- Redis和MySQL数据一致性问题,有没有好的解决方案?
- JS中对事件代理的理解及其应用场景
- Industrial control network intrusion detection based on automatic optimization of hyperparameters
- 好的期货公司开户让人省心省钱
- 期货开户手续费加一分是主流
- c语言字符和字符串函数总结(二)
- What does the errorPage attribute of the JSP page directive do?
- 什么是低代码(Low-Code)?低代码适用于哪些场景?
猜你喜欢
随机推荐
nodeJs--mime module
go mode tidy出现报错go warning “all“ matched no packages
傅立叶变换相关公式
期货开户手续费的秘密成了透明
PHP to read data from TXT file
DOA从一维阵列传感说起
ERROR 1045 (28000) Access denied for user ‘root‘@‘localhost‘解决方法
Redis和MySQL数据一致性问题,有没有好的解决方案?
Knowing the inorder traversal of the array and the preorder traversal of the array, return the postorder history array
如何期货开户和选择期货公司?
Web开发
Industrial control network intrusion detection based on automatic optimization of hyperparameters
C language character and string function summary (2)
简单工厂模式
22.卷积神经网络实战-Lenet5
IDEA找不到Database解决方法
管理基础知识20
ICML 2022 | GraphFM:通过特征Momentum提升大规模GNN的训练
使用jOOQ将Oracle风格的隐式连接自动转换为ANSI JOIN
管理基础知识15