2014-03-18 01:30

题目:反转一个char *型的C/C++字符串。

解法:一头一尾俩iterator,向中间靠拢并且交换字符。

代码:

 1 // 1.2 Implement a function void reverse(char *str) in C or C++ which reverses a null-terminated string.
 2 #include <cstdio>
 3 #include <cstring>
 4 using namespace std;
 5 
 6 void reverse(char *str)
 7 {
 8     if (nullptr == str) {
 9         return;
10     }
11 
12     size_t i;
13     size_t len = strlen(str);
14     char ch;
15 
16     for (i = 0; i < len - 1 - i; ++i) {
17         ch = str[i];
18         str[i] = str[len - 1 - i];
19         str[len - 1 - i] = ch;
20     }
21 }
22 
23 int main()
24 {
25     char str[1000];
26 
27     while (scanf("%s", str) == 1) {
28         reverse(str);
29         printf("%s\n", str);
30     }
31 
32     return 0;
33 }

 

 posted on 2014-03-18 01:32  zhuli19901106  阅读(544)  评论(0编辑  收藏  举报