这是一个不使用任何库函数的单行(需要声明变量): -
char s [] = "hello world";
char *p,*q;
for (p=s,q=0;p>q;q?*p^=*q,*q^=*p,*p--^=*q++:!*++p?q=s,*--p:0);
Run Code Online (Sandbox Code Playgroud)
解释代码如何工作: -
变量: -
状态:-
终止:-
当指向字符串前半部分的指针超出指向字符串后半部分的指针时,循环终止.在搜索字符串结尾时,指向前半部分(q)的指针为0,因此条件始终为真.
递增: -
for循环的第三部分取决于状态,可以像这样分解: -
if state is searching for end of string (q == 0)
increment end of string pointer (++p)
if end of string pointer is pointing at null terminator (*p == 0)
set start of string pointer and set state to swapping characters (q=s)
decrement end of string pointer (--p)
endif
else
swap characters (the three ^=)
move first and secondhalf pointers (--p, ++q)
endif
Run Code Online (Sandbox Code Playgroud)
究其原因,显然不必要*在*--p是保证三元运营商的所有部分具有相同的类型.
如果您了解所有这些,那么您应该发现代码中的错误.
一个需求"的行最少数量"不会使该多大意义(毕竟,整个程序可以在一行中写的).如果您愿意进行就地反转,您可以使用相当轻量级的实现:
void strrev(char *s) {
char *p = s + strlen(s);
while ( s + 1 < p ) {
char tmp = *s;
*s++ = *--p;
*p = tmp;
}
}
Run Code Online (Sandbox Code Playgroud)