Home > Backend Development > C++ > body text

C program to sort names alphabetically

WBOY
Release: 2023-09-24 22:49:02
forward
1522 people have browsed it

C program to sort names alphabetically

用户必须输入姓名的数量,并且这些姓名需要使用strcpy()函数按字母顺序排序。

字符数组(或字符集合)被称为字符串。

声明

以下是数组的声明:

char stringname [size];
Copy after login

例如,char string[50]; 长度为50个字符的字符串。

初始化

  • 使用单个字符常量
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
Copy after login
  • 使用字符串常量
char string[10] = "Hello":;
Copy after login

访问

有一个控制字符串“%s”用于访问字符串,直到遇到“\0”为止

strcpy()

这个函数用于将源字符串复制到目标字符串中。

目标字符串的长度大于或等于源字符串。

strcpy()函数的语法如下:

strcpy (Destination string, Source String);
Copy after login

例如,

char a[50];             char a[50];
strcpy ("Hello",a);      strcpy ( a,"hello");
output: error           output: a= "Hello"
Copy after login

用于按字母顺序对名称进行排序的逻辑如下 -

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);
      }
   }
}
Copy after login

程序

以下是按字母顺序对名称进行排序的 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]);
   }
}
Copy after login

输出

当上述程序被执行时,它产生以下结果 −

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
Copy after login

The above is the detailed content of C program to sort names alphabetically. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!