C언어 문자열 정렬
문자열 교체 및 문자열 정렬
string 함수 => strcmp, strcpy
strcmp
같으면 0, 좌측이 크면 1, 좌측이 작으면 -1
aa : aa => 0
ab : aa => 1
aa : ab => -1
strcmp("aa","ab")
int main() { char name[5][10]; int i, j, n; char tmp[10]; n = sizeof(name) / sizeof(char[10]); printf("%d명의 이름 입력\n", n); printf("-----------------------------------------\n"); for (i = 0; i<n; i++) { printf("%d번째 이름 : ", i+1); scanf("%s", &name[i]); } printf("-----------------------------------------\n"); puts(" \n * 입 력 받 은 데 이 터 출 력 * "); for (i = 0; i<n; i++) { printf("%d번 째 이름 ==> %s \n", i+1, name[i]); } printf("-----------------------------------------\n"); //정렬 strcmp => 교체 strcpy for (i = 0; i<n - 1; i++) { for (j = 0; j<n - 1 - i; j++) { if (strcmp(name[j], name[j + 1]) > 0) { strcpy(tmp, name[j]); strcpy(name[j], name[j + 1]); strcpy(name[j + 1], tmp); } } } printf("-----------------------------------------\n"); puts(" \n * 정 렬 결과 * "); for (i = 0; i<n; i++) { printf("%d번 째 이름 ==> %s \n", i+1, name[i]); } return 0; } |
|
strtok
공백 분리
#include <stdio.h> #include <string.h> int main() { char str[] = "Our newest designs are dynamic and looking towards the future."; char *tok; printf("문장 : %s\n", str); tok = strtok(str, " ");//한칸띄움 while (tok != NULL) { printf("%s \n", tok); tok = strtok(NULL, " "); } return 0; } |
|
strchr
위치를 찾아 포인터를 리턴
#include <stdio.h> #include <string.h> int main() { char str[] = "Our newest designs are dynamic and looking towards the future."; printf("문장 : %s\n", str); printf("t를 찾고, 그 다음 글자들은 : %s", strchr(str, 't'));
return 0; } |
|