merge

Run Settings
LanguageC
Language Version
Run Command
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define M 20 // 数组元素最多个数 #define N 15 // 单词最大长度,包括 '\0' size_t gets_to_array(char a[][N]) { int ch, last_space = 0; size_t i = 0, j = 0; while (ch = getchar(), ch != EOF && ch != '\n') { if (isspace(ch)) { if (!last_space) { a[i++][j] = '\0'; last_space = 1; j = 0; } } else { a[i][j++] = (char)ch; last_space = 0; } } return i + 1; } int cmp_str(const void *a, const void *b) { return strcmp(a, b); } size_t merge_arrays(char a[][N], size_t n, char b[][N], size_t m, char c[][N]) { qsort(a, n, sizeof(a[0]), cmp_str); qsort(b, m, sizeof(b[0]), cmp_str); size_t i, j, k; for (i = 0, j = 0, k = 0; i < n && j < m;) { if (strcmp(a[i], b[j]) <= 0) { if (k == 0 || strcmp(c[k - 1], a[i]) != 0) strcpy(c[k++], a[i]); i++; } else { if (k == 0 || strcmp(c[k - 1], b[j]) != 0) strcpy(c[k++], b[j]); j++; } } for (; i < n; ++i) if (k == 0 || strcmp(c[k - 1], a[i]) != 0) strcpy(c[k++], a[i]); for (; j < m; ++j) if (k == 0 || strcmp(c[k - 1], b[j]) != 0) strcpy(c[k++], b[j]); return k; } void show_array(char a[][N], size_t n) { printf("{ "); for (size_t i = 0; i < n; ++i) { printf(i == n - 1 ? "%s" : "%s, ", a[i]); } printf(" }\n"); } int main() { char A[M][N]; char B[M][N]; char C[M * 2][N]; size_t lenA = gets_to_array(A); size_t lenB = gets_to_array(B); size_t lenC = merge_arrays(A, lenA, B, lenB, C); show_array(A, lenA); show_array(B, lenB); show_array(C, lenC); }
Editor Settings
Theme
Key bindings
Full width
Lines