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