fork download
  1. #include <stddef.h>
  2. #include <ctype.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <stdio.h>
  6.  
  7. static int in_set(
  8. register const int c,
  9. register const char * chars
  10. ) {
  11. register int test;
  12.  
  13. while ((test = *chars)) {
  14. if (c == test)
  15. return 1;
  16. ++chars;
  17. continue;
  18. }
  19. return 0;
  20. }
  21.  
  22. char * rstrip(
  23. register const char * const string,
  24. register const char * const chars
  25. ) {
  26. register char c;
  27. register const char * cur_pos = string;
  28. register const char * one_past_end = string + 1;
  29. register ptrdiff_t diff;
  30. register char * copy;
  31.  
  32. if (!chars) {
  33. while ((c = *cur_pos)) {
  34. if (!isspace(c))
  35. one_past_end = cur_pos + 2;
  36. ++cur_pos;
  37. continue;
  38. }
  39. } else {
  40. while ((c = *cur_pos)) {
  41. if (!in_set(c, chars))
  42. one_past_end = cur_pos + 2;
  43. ++cur_pos;
  44. continue;
  45. }
  46. }
  47. diff = one_past_end - string;
  48. copy = malloc(diff);
  49. if (!copy)
  50. return NULL;
  51.  
  52. --diff;
  53. copy[diff] = '\0';
  54. return memcpy(copy, string, diff);
  55. }
  56.  
  57. int main(void) {
  58. char * tests[] = {
  59. "",
  60. " ",
  61. " ",
  62. "f",
  63. " f",
  64. " f",
  65. " f ",
  66. " f ",
  67. "f ",
  68. "f ",
  69. "foo bar baz",
  70. " foo bar baz",
  71. " foo bar baz",
  72. " foo bar baz ",
  73. " foo bar baz ",
  74. "foo bar baz ",
  75. "foo bar baz ",
  76. "mississippi",
  77. };
  78. int i;
  79. char * stripped;
  80.  
  81. for (i = 0; i < (sizeof tests / sizeof *tests) - 1; ++i) {
  82. stripped = rstrip(tests[i], NULL);
  83. if (stripped)
  84. printf("[%s]\n", stripped);
  85. free(stripped);
  86. continue;
  87. }
  88. stripped = rstrip(tests[i], "ipz");
  89. if (stripped)
  90. printf("[%s]\n", stripped);
  91. free(stripped);
  92.  
  93. return EXIT_SUCCESS;
  94. }
  95.  
Success #stdin #stdout 0.02s 1852KB
stdin
Standard input is empty
stdout
[]
[]
[]
[f]
[ f]
[   f]
[   f]
[   f]
[f]
[f]
[foo bar   baz]
[ foo bar   baz]
[                  foo bar   baz]
[                  foo bar   baz]
[ foo bar   baz]
[foo bar   baz]
[foo bar   baz]
[mississ]