fork(1) download
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. void trim_right(char *s) {
  5. char *space_pos = NULL;
  6. for(;;++s) {
  7. char ch = *s;
  8. if(ch == '\0') {
  9. break;
  10. } else if(ch == ' ') {
  11. if(!space_pos)
  12. space_pos = s;
  13. } else {
  14. space_pos = NULL;
  15. }
  16. }
  17. if(space_pos) {
  18. *space_pos = '\0';
  19. }
  20. }
  21.  
  22. char buf[1024];
  23. void test(const char *arg, const char *expected) {
  24. snprintf(buf, sizeof(buf), "%s", arg);
  25. trim_right(buf);
  26. if(strcmp(buf, expected) == 0) {
  27. printf("OK: '%s' -> '%s'\n", arg, expected);
  28. } else {
  29. printf("FAIL: arg is '%s', expected '%s', found '%s'.\n", arg, expected, buf);
  30. }
  31. }
  32.  
  33. int main(void) {
  34. test("", "");
  35. test("word", "word");
  36. test(" foo ", " foo");
  37. test(" bar ", " bar");
  38. test(" ", "");
  39. test("this failure is expected", "...");
  40. return 0;
  41. }
  42.  
Success #stdin #stdout 0s 2160KB
stdin
Standard input is empty
stdout
OK: '' -> ''
OK: 'word' -> 'word'
OK: ' foo ' -> ' foo'
OK: ' bar   ' -> ' bar'
OK: '     ' -> ''
FAIL: arg is 'this failure is expected', expected '...', found 'this failure is expected'.