C语言程序按字母顺序排序姓名
用户需要输入姓名数量,并使用strcpy()函数按字母顺序对这些姓名进行排序。
字符数组(或)字符集合称为字符串。
声明
以下是数组的声明:
char stringname [size];
例如,char string[50]; 长度为50个字符的字符串。
初始化
- 使用单字符常量
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}- 使用字符串常量
char string[10] = "Hello":;
访问
有一个控制字符串"%s" 用于访问字符串,直到遇到‘\0’
strcpy ( )
此函数用于将源字符串复制到目标字符串中。
目标字符串的长度大于或等于源字符串。
strcpy()函数的语法如下:
strcpy (Destination string, Source String);
例如,
char a[50]; char a[50];
strcpy ("Hello",a); strcpy ( a,"hello");
output: error output: a= "Hello"用于按字母顺序对姓名进行排序的逻辑如下:
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(strcmp(str[i],str[j])>0){
strcpy(s,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],s);
}
}
}程序
以下是按字母顺序对姓名进行排序的C语言程序:
#include<stdio.h>
#include<string.h>
main(){
int i,j,n;
char str[100][100],s[100];
printf("Enter number of names :
");
scanf("%d",&n);
printf("Enter names in any order:
");
for(i=0;i<n;i++){
scanf("%s",str[i]);
}
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(strcmp(str[i],str[j])>0){
strcpy(s,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],s);
}
}
}
printf("
The sorted order of names are:
");
for(i=0;i<n;i++){
printf("%s
",str[i]);
}
}输出
执行上述程序时,将产生以下结果:
Enter number of names: 5 Enter names in any order: Pinky Lucky Ram Appu Bob The sorted order of names is: Appu Bob Lucky Pinky Ram
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP