
用户必须输入姓名的数量,并且这些姓名需要使用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 (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 :</p><p>");
scanf("%d",&n);
printf("Enter names in any order:</p><p>");
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("</p><p>The sorted order of names are:</p><p>");
for(i=0;i<n;i++){
printf("%s</p><p>",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
以上就是C程序按字母顺序排序姓名的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号