사용자는 이름의 개수를 입력해야 하며, 그 이름은 strcpy() 함수를 사용하여 알파벳순으로 정렬되어야 합니다.
문자 배열(또는) 문자 모음을 문자열이라고 합니다.
선언
다음은 배열에 대한 선언입니다 -
char stringname [size];
예를 들어, char string[50]; 길이 50자의 문자열.
초기화
- 단일 문자 상수 사용
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’} - 문자열 상수 사용
char string[10] = "Hello":;
액세스
'\0'이 나타날 때까지 문자열에 액세스하는 데 사용되는 제어 문자열 "%s"가 있습니다.
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 :\n");
scanf("%d",&n);
printf("Enter names in any order:\n");
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("\nThe sorted order of names are:\n");
for(i=0;i<n;i++){
printf("%s\n",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