使用strncpy去除后面的空格 /* 2136 Vertical Histogram */ #include <iostream> #include <cstdio> #include <cstdlib> #include <cctype> #include <string> #include <cstring> using namespace std; inline void RemoveEndSpace(char * str1, char * str2) { int len = strlen(str1) - 1; while (str1[len] == ' ') len --; strncpy(str2, str1, len + 1); // strcat(str2, "$"); // debug } int main() { int c[26] = {0}; char ch; while (cin >> ch) if (isupper(ch)) ++ c[ch - 'A']; int max = 0; for (int i = 1; i < 26; ++ i) if (c[i] > c[max]) max = i; max = c[max]; char str1[100], str2[100]; while (max) { memset(str1, 0, sizeof str1); memset(str2, 0, sizeof str2); for (int j = 0; j < 26; ++ j) { if (c[j] >= max) { strcat(str1, "* "); } else strcat(str1, " "); } RemoveEndSpace(str1, str2); puts(str2); -- max; } cout << "A"; for (ch = 'B'; ch <= 'Z'; ++ ch) { cout << " " << ch; } cout << endl; return 0; }