简体   繁体   English

如何使用C反转字符串?

[英]How to reverse string using C?

I want to reverse a string in the C language. 我想反转C语言中的字符串。 I'm kinda new, so I would love to get some help and explanation. 我有点新,所以我很想获得帮助和解释。 Why doesn't my solution work? 为什么我的解决方案不起作用?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>

char *rev(char *str) {
  char *q = str;
  int len = strlen(str);
  char *p = (char*)calloc(len+1, sizeof(char));
  int j=0;
  if (NULL == str || len == 1) return str;
  for (j = len+1 ; j > 0 ; j-- ) {
    p[j]=*q;
    q++;
  }
  return p;
}

int main(int argc, char **argv){
  char *t = argv[1];
  char *p ;
  printf("%s",t);
  p=rev(t);
  printf("%s",p);
  getchar();
  return 0;
}

It's not working :( 它不起作用:(

First, you were smart to use calloc to make sure your result buffer had a zero at the end. 首先,您很聪明地使用calloc来确保结果缓冲区的末尾为零。

But it also put the zero at the beginning! 但这也将零开头!

Your loop termination condition was j > 0 meaning you never filled slot 0 in the result. 循环终止条件是j > 0这意味着您永远不会在结果中填充插槽0。

So when you try to print p , the first character in the buffer it points to contains a \\0 -- marking the end of a string, so your result is always the empty string . 因此,当您尝试打印p ,缓冲区中的第一个字符指向一个\\0标记字符串的结尾,因此结果始终是空字符串

I've done a little "fix" at http://codepad.org/QppfYQkm (I did not change the formatting, and I hardcoded the argument so it would be self-contained.) 我在http://codepad.org/QppfYQkm上做了一些“修复”(我没有更改格式,并且对参数进行了硬编码,因此它是独立的。)

Aside: I removed your check for if (len == 1) return str . 撇开:我删除了您检查if (len == 1) return str Do not do this! 不要这样做! If you have a one-character string, you will be returning the same buffer as that which held your argument, meaning changes to that result would destroy your input. 如果您使用一个字符的字符串,则将返回与保存参数的缓冲区相同的缓冲区,这意味着更改该结果将破坏您的输入。 Keep these buffers separate. 将这些缓冲区分开。

You were really close. 你真的很亲近 :) :)

ADDENDUM 附录

Here is some code using a commandline argument: 这是一些使用命令行参数的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>

char *rev(char *str) {
  char *q = str;
  int len = strlen(str);
  char *p = (char*)calloc(len + 1, sizeof(char));
  int j;

  if (NULL == str) return NULL;

  for (j = len-1 ; j >= 0 ; j--) {
    p[j] = *q;
    q++;
  }
  return p;
}

int main(int argc, char **argv) {
  if (argc > 1) {
    char *t = argv[1];
    char *p ;

    printf("%s\n",t);
    p = rev(t);
    printf("%s\n",p);

    return 0;
  }
}

When I run it: 当我运行它时:

$ gcc rev.c && ./a.out "hello there, reverse me"
hello there, reverse me
em esrever ,ereht olleh
$ gcc rev.c && ./a.out ""


$ gcc rev.c && ./a.out
$

The program works fine with text and with the empty string. 该程序可以很好地处理文本和空字符串。 It silently does nothing when given no argument. 没有给出任何参数时,它默默地不执行任何操作。

You have to be careful with your indices at the boundaries. 您必须小心边界处的索引。

One way to fix is replace your for line with this: 一种解决方法是用以下代码替换for行:

for (j = len-1; j >= 0 ; j-- )

You need to iterate over half the list (rounding down, the middle character can't be reversed if it's an odd-lengthed string), and then swap it via a temporary variable. 您需要迭代列表的一半以上(四舍五入,如果中间字符是奇长字符串,则不能反转中间字符),然后通过一个临时变量进行交换。

You are writing over half your string because you're not using a temporary variable. 您正在写一半以上的字符串,因为您没有使用临时变量。 Try something like: 尝试类似:

for( j = 0; j < len / 2; ++j ) {
    char tmp = p[ j ];
    p[ j ] = p[ len - j - 1 ];
    p[ len - j - 1 ] = tmp;
}

Edit: this does it in place; 编辑:这样做就位; if you were doing it into another buffer you'll need to add p[len] = 0; 如果将其放入另一个缓冲区,则需要添加p [len] = 0;

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

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