繁体   English   中英

使用指针反转字符串

[英]Reversing a string using pointers

我目前正在研究不同的算法来练习编码强度,并遇到了将字符串反向的算法。 它使用了指针,我对正在发生的事情有点困惑。 代码如下:

void reverse(char *str) {
   char * end = str;
   char tmp;
   if (str) {
      while (*end) {
         ++end;
      }
  --end;
  while (str < end) {
     tmp = *str;
     *str++ = *end;
     *end-- = tmp;
  }
 }
}

因此,在此代码中,将末尾放在第一个while循环中字符串存储位置的末尾。 然后第二个时刻让我感到困惑。 我不明白* str ++ = * end和* end-- = * temp的情况。

为什么会这样呢? 当出现行tmp = * str时,字符串的第一个字母进入temp还是我不正确地想到了这一点?

如您所知, end指向最后一个字符。 现在,在第二个for循环中,他只是将第一个字符与最后一个字符交换,然后将str指针移向其右侧并向左移动。

while (str < end) {
     tmp = *str;  // storing the char at str in temp
     *str++ = *end;  // storing the char at end at str position and then incrementing str .. i.e. moving str right
     *end-- = tmp;  // storing the char in tmp at end position and then decrementing tmp .. i.e. moving tmp left 
  }

始终最好尝试一个示例,以下是单词"hello"的第二个while循环的样子。 *str的值始终存储在tmp ,然后将*end复制到*str ,总体效果是,每次迭代后, *str*end的值都会切换。 *str的后递增和*end的后递减直到赋值语句之后才生效。

    *end
    v
hello        tmp='h'
^
*str
------------------
   *end
   v
oellh        tmp='e'
 ^
 *str
------------------
  *end
  v
olleh        tmp='e'
  ^
  *str

执行在此停止,因为str < end产生错误的值,因为它们现在都指向同一字符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM