你如何扭转发生在C或C ++字符串? [英] How do you reverse a string in place in C or C++?

查看:133
本文介绍了你如何扭转发生在C或C ++字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何扭转C或C ++字符串,而不需要单独的缓冲区来保存逆转字符串?

How do you reverse a string in C or C++ without requiring a separate buffer to hold the reversed string?

推荐答案

邪恶C:

#include <stdio.h>

void strrev(char *p)
{
  char *q = p;
  while(q && *q) ++q;
  for(--q; p < q; ++p, --q)
    *p = *p ^ *q,
    *q = *p ^ *q,
    *p = *p ^ *q;
}

int main(int argc, char **argv)
{
  do {
    printf("%s ",  argv[argc-1]);
    strrev(argv[argc-1]);
    printf("%s\n", argv[argc-1]);
  } while(--argc);

  return 0;
}

(这是异或交换的事情。小心注意,您的必须避免的自交换,因为^一个== 0)。

(This is XOR-swap thing. Take care to note that you must avoid swapping with self, because a^a==0.)

#include <bits/types.h>
#include <stdio.h>

#define SWP(x,y) (x^=y, y^=x, x^=y)

void strrev(char *p)
{
  char *q = p;
  while(q && *q) ++q; /* find eos */
  for(--q; p < q; ++p, --q) SWP(*p, *q);
}

void strrev_utf8(char *p)
{
  char *q = p;
  strrev(p); /* call base case */

  /* Ok, now fix bass-ackwards UTF chars. */
  while(q && *q) ++q; /* find eos */
  while(p < --q)
    switch( (*q & 0xF0) >> 4 ) {
    case 0xF: /* U+010000-U+10FFFF: four bytes. */
      SWP(*(q-0), *(q-3));
      SWP(*(q-1), *(q-2));
      q -= 3;
      break;
    case 0xE: /* U+000800-U+00FFFF: three bytes. */
      SWP(*(q-0), *(q-2));
      q -= 2;
      break;
    case 0xC: /* fall-through */
    case 0xD: /* U+000080-U+0007FF: two bytes. */
      SWP(*(q-0), *(q-1));
      q--;
      break;
    }
}

int main(int argc, char **argv)
{
  do {
    printf("%s ",  argv[argc-1]);
    strrev_utf8(argv[argc-1]);
    printf("%s\n", argv[argc-1]);
  } while(--argc);

  return 0;
}


  • 为什么,是的,如果输入borked,这会乐呵呵地交换以外的地方。

  • 有用的链接在UNI code捣毁时: http://www.macchiato.com/ UNI code /图表/

  • 此外,UTF-8在0x10000的是未经检验的(因为我似乎没有对任何字体,也没有耐心用16进制软件)

  • 例如:

    $ ./strrev Räksmörgås ░▒▓○◔◑◕●
    
    ░▒▓○◔◑◕● ●◕◑◔○▓▒░
    
    Räksmörgås sågrömskäR
    
    ./strrev verrts/.
    

    这篇关于你如何扭转发生在C或C ++字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆