题解 | #字符串排序#
字符串排序
http://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
#include <stdio.h> #include <string.h> #include <ctype.h> void sort(char *string) { unsigned long len, i ,j, k; char ch1, ch2, tmp; len = strlen(string); for (i = 0; i < len - 1; i++) { for (j = 0; j < len - i; j++) { if (!isalpha(string[j])) { continue; } k = j; while ((!isalpha(string[++k])) && (k < (len - i))); if (k >= (len - i)) { continue; } ch1 = tolower(string[j]); ch2 = tolower(string[k]); if (ch1 > ch2) { tmp = string[j]; string[j] = string[k]; string[k] = tmp; } } } } int main() { #define LINE_SIZE (1024) char *p, *str; int ret, len = 0, str_size = LINE_SIZE; str = malloc(str_size); if (NULL == str) { return -1; } while (1) { p = fgets(str + len, str_size - len, stdin); if (NULL == p) { break; } len = strlen(str); if (('\n' != str[len - 1]) && (len == str_size - 1)) { str_size += LINE_SIZE; str = realloc(str, str_size); continue; } len = 0; if (str[0]) { sort(str); printf("%s", str); } } free(str); return 0; }