[ create a new paste ] login | about

Link: http://codepad.org/HThtwzhh    [ raw code | output | fork ]

mohit_at_codepad - C, pasted on Jun 17:
#include <stdio.h>
#include <string.h>
#define MAX_LEN_OF_STRING 500

void reverse_(char *b, char *e) {
  if(!b || !e || b >= e--) return;
  while(b < e) {
    char t = *b;
    *b++ = *e;
    *e-- = t;
  }
}

/** 
 * Reverse each space separated words in a string
 *
 * @param [in] str String to reverse words
 *
 * @ret Reversed string if successful
 * @ret NULL if failed (length of string is more than expected)
 *
 * Returned string may be no more valid after another call to
 * reverseWords or reverseWordOrder.
 */
char *reverseWords(char *str) {
  static char ans[MAX_LEN_OF_STRING + 1];
  size_t len = strlen(str);
  if(len <= MAX_LEN_OF_STRING) {
    char *b = ans;
    strcpy(ans, str);
    do {
      char *e = b;
      while(*e != ' ' && *e != '\0') ++e;
      reverse_(b, e);
      b = e;
      while(*b == ' ') ++b;
    } while(*b != '\0');
    return ans;
  } else {
    return NULL;
  }
}

/** 
 * Reverse the order of each space separated words in a string
 *
 * @param [in] str String to reverse word orders
 *
 * @ret Reversed string if successful
 * @ret NULL if failed (length of string is more than expected)
 *
 * Returned string may be no more valid after another call to
 * reverseWords or reverseWordOrder.
 */
char *reverseWordOrder(char *str) {
  char *t = reverseWords(str);
  if(NULL != t) {
    size_t len = strlen(t);
    reverse_(t, t+len);
  }
  return t;
}

int main() {
  char test_str[] = "This is a test string";
  printf("Input = %s\n", test_str);
  printf("reverseWords = %s\n", reverseWords(test_str));
  printf("reverseWordOrder= %s\n", reverseWordOrder(test_str));
  return 0;
}


Output:
1
2
3
Input = This is a test string
reverseWords = sihT si a tset gnirts
reverseWordOrder= string test a is This


Create a new paste based on this one


Comments: