Saturday, August 3, 2013

Coding Exercises Day 1b (Problem #2)

Problem:
Implement a function in C which reverses a null-terminated string.

void reverse(char* str) {
  
  int length = strlen(str);

  if (length > 1) {

    int startIdx = 0;
    int endIdx = length - 1;
    
    while (startIdx < endIdx) { 
      char temp = str[startIdx];
      str[startIdx] = str[endIdx];
      str[endIdx] = temp;

      endIdx--;
      startIdx++;
    }
  }
}

No comments:

Post a Comment