简体   繁体   English

为什么我的“反向”字符串C函数不起作用?

[英]why is my 'reverse' string C function not working?

I'm trying to write a function to reverse the characters in a string in C, but it's not working. 我正在尝试编写一个函数来反转C语言字符串中的字符,但是它不起作用。

This is what I have: 这就是我所拥有的:

/* ... the  */
char str[1000];
strcpy(&str[0], &text[0]); // get the values from existing 'char text[1000]' 

if (DEBUG) printf("DEBUG: str value before reverse: %s\n", str); 
// reverse the string
reverse(&str[0]);
if (DEBUG) printf("DEBUG: str value after reverse: %s\n", str); 
/* ... */

After calling 'reverse', my output looks like this: 调用“ reverse”后,我的输出如下所示:

DEBUG: str value before reverse: this is a line of text
DEBUG: str value after reverse: 

Here's my function: 这是我的功能:

void reverse(char * str)
{
  char str2[1000];
  int i = 0;
  // find the null in str
  while (str[i] != '\0') {
    i++;
  }
  // now put the chars from str into str2 in the reverse order
  int j = 0;
  while (i >= 0) {
    str2[j] = str[i];
    i--;
    j++;
  }
  str2[j] = '\0';
  // now str2 contains the reverse of str, copy it to str
  strcpy(&str[0], &str2[0]);
  return;
}

What's wrong with it? 它出什么问题了? And is there an easier way to reverse a string? 还有更简单的方法来反转字符串吗?

What's wrong with it? 它出什么问题了?

After the first loop completes, str[i] is equal to 0. Therefore the first iteration of the second loop stores the null terminator at the first position of str2 , making it effectively a string of length 0. Of course it then goes on and writes additional characters to the buffer, but those will be ignored by any function you use. 在第一个循环完成之后, str[i]等于0。因此,第二个循环的第一次迭代将空终止符存储在str2的第一个位置,从而使其有效地成为长度为0的字符串。将其他字符写入缓冲区,但是您使用的任何函数都会忽略这些字符。

And is there an easier way to reverse a string? 还有更简单的方法来反转字符串吗?

Sure. 当然。 For example, this implementation reverses a string in-place without allocating additional buffers: 例如, 此实现在不分配其他缓冲区的情况下就地反转字符串:

char *strrev(char *str)
{
      char *p1, *p2;

      if (! str || ! *str)
            return str;
      for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)
      {
            *p1 ^= *p2;
            *p2 ^= *p1;
            *p1 ^= *p2;
      }
      return str;
}

当str [i]为'\\ 0'时,您开始复制,因此您的字符串将以它开头并且为空。

I figured it out. 我想到了。

After the first while loop, i is the location of the '\\0' and I'm making it the first character of str2, so str is always empty string. 在第一个while循环之后,i是'\\ 0'的位置,并且使它成为str2的第一个字符,因此str始终为空字符串。

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

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