1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| void swap (char chars[], int p, int q); void reverse (char chars[], int start, int end); void reverseWords(char strings[]);
int main(int argc, const char * argv[]) { @autoreleasepool { char string[] = "the sky is blue"; reverseWords(string); } return 0; }
void swap (char chars[], int p, int q) { char temp = chars[p]; chars[p] = chars[q]; chars[q] = temp; }
void reverse (char chars[], int start, int end) { NSLog(@"%s",chars); int s = start; int e = end;
while (s < e) { swap(chars, s, e); s += 1; e -= 1; } NSLog(@"%s",chars); }
void reverseWords(char strings[]) { if ((int)strlen(strings) == 0) { return; } int start = 0, len = (int)strlen(strings); reverse(strings, 0, len - 1); for (int i = 0 ; i < len; i++) { if ((i == len - 1) || (strings[i + 1] == ' ')) { reverse(strings, start, i); start = i + 2; } } NSLog(@"%s",strings); }
|