简体   繁体   English

使用指针反转字符串

[英]Reversing a string using pointers

I am currently studying different algorithms to practice my coding strengths and came across an alogrithm to reverse a string. 我目前正在研究不同的算法来练习编码强度,并遇到了将字符串反向的算法。 It uses pointers and I am alittle confused on what is going on. 它使用了指针,我对正在发生的事情有点困惑。 The code is below: 代码如下:

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

So in this code, the end is put to the end of the strings memory location in the first while loop. 因此,在此代码中,将末尾放在第一个while循环中字符串存储位置的末尾。 Then the second while is where I am getting confused. 然后第二个时刻让我感到困惑。 I do not understand what is going with the *str++ = *end and *end-- = *temp. 我不明白* str ++ = * end和* end-- = * temp的情况。

Why is this happening like this? 为什么会这样呢? When the line tmp = *str occurs, does the first letter of the string go into temp or am I thinking of this incorrectly? 当出现行tmp = * str时,字符串的第一个字母进入temp还是我不正确地想到了这一点?

As you already know end points to the last character. 如您所知, end指向最后一个字符。 Now in the second for loop he is just swapping the first character with the last character and then moving the str pointer towards its rights and end to its left. 现在,在第二个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 
  }

It is always best to try an example, below is what the second while loop would look like for the word "hello" . 始终最好尝试一个示例,以下是单词"hello"的第二个while循环的样子。 The value of *str is always stored in tmp , then *end is copied into *str , the overall effect is that after each iteration the values of *str and *end switch. *str的值始终存储在tmp ,然后将*end复制到*str ,总体效果是,每次迭代后, *str*end的值都会切换。 Both the post-increment on *str and the post-decrement on *end do not take effect until after the assignment statements. *str的后递增和*end的后递减直到赋值语句之后才生效。

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

execution stops here because str < end produces a false value since they now both point to the same character. 执行在此停止,因为str < end产生错误的值,因为它们现在都指向同一字符。

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

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