fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <ctype.h>
  5.  
  6. // a) Xóa khoảng trắng thừa giữa các từ
  7. void simplifySpaces(char *str) {
  8. int i = 0, j = 0;
  9. int space = 1; // ban đầu đang là khoảng trắng
  10.  
  11. while (str[i]) {
  12. if (!isspace(str[i])) {
  13. if (j != 0) str[j++] = ' ';
  14. while (str[i] && !isspace(str[i])) {
  15. str[j++] = str[i++];
  16. }
  17. } else {
  18. i++;
  19. }
  20. }
  21. str[j] = '\0';
  22. }
  23.  
  24. // b) Viết hoa chữ cái đầu mỗi từ, còn lại viết thường
  25. void formatCapitalization(char *str) {
  26. int newWord = 1;
  27. for (int i = 0; str[i]; i++) {
  28. if (isspace(str[i])) {
  29. newWord = 1;
  30. } else {
  31. if (newWord) {
  32. str[i] = toupper(str[i]);
  33. newWord = 0;
  34. } else {
  35. str[i] = tolower(str[i]);
  36. }
  37. }
  38. }
  39. }
  40.  
  41. // c) Đảo thứ tự các từ
  42. void reverseWords(char *str) {
  43. char *words[100];
  44. int count = 0;
  45.  
  46. // Tách từ
  47. char *token = strtok(str, " ");
  48. while (token != NULL) {
  49. words[count++] = token;
  50. token = strtok(NULL, " ");
  51. }
  52.  
  53. // In ngược lại
  54. for (int i = count - 1; i >= 0; i--) {
  55. printf("%s", words[i]);
  56. if (i > 0) printf(" ");
  57. }
  58. printf("\n");
  59. }
  60.  
  61. int main() {
  62. char str[1000] = " HUyNh gIA HaO ";
  63.  
  64. printf("Xau goc: \"%s\"\n", str);
  65.  
  66. // a) Đơn giản hóa khoảng trắng
  67. simplifySpaces(str);
  68. printf("a) Sau khi xoa khoang trang thua: \"%s\"\n", str);
  69.  
  70. // b) Viết hoa chữ cái đầu
  71. formatCapitalization(str);
  72. printf("b) Viet hoa chu cai dau moi tu: \"%s\"\n", str);
  73.  
  74. // c) Đảo thứ tự từ
  75. printf("c) Dao thu tu cac tu: \"");
  76. reverseWords(str); // đã chỉnh sửa trực tiếp trên str
  77. printf("\"\n");
  78.  
  79. return 0;
  80. }
  81.  
Success #stdin #stdout 0.01s 5288KB
stdin
    HUynh gIA HaO      
stdout
Xau goc: "  HUyNh    gIA     HaO  "
a) Sau khi xoa khoang trang thua: "HUyNh gIA HaO"
b) Viet hoa chu cai dau moi tu: "Huynh Gia Hao"
c) Dao thu tu cac tu: "Hao Gia Huynh
"