是否有可能写的,可以扭转一个字符串不使用缓冲区字符串的函数? [英] Is it possible write a function that can reverse a string without using a buffer string?

查看:189
本文介绍了是否有可能写的,可以扭转一个字符串不使用缓冲区字符串的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/2124600/how-to-reverse-a-string-in-place-in-c-using-pointers\">How使用指针,以扭转在C处字符串?

面试问题是像 - 编写一个函数调用revstr可以采取一个字符串,扭转它不使用字符串缓冲区即涉及指针等。

The interview question was like - write a function called revstr which can take a string and reverse it without using a buffer string i.e involving pointers etc .

推荐答案

从开始迭代,同时结束,互换角色。

Iterate from beginning and end simultaneously, swap characters.

void revstr(char * str) {
  int right = strlen(str) - 1;
  int left = 0;
  while (left < right) {
    char c = str[right];
    str[right] = str[left];
    str[left] = c;
    ++left;
    --right;
  }
}

您也可以选择使用XOR技巧无需中间炭交换:

Optionally you can use xor tricks to swap without an intermediate char:

str[right] ^= str[left];
str[left] ^= str[right];
str[right] ^= str[left];

这是做交换的纯粹荒谬的方式 - 使用这种结构的唯一原因是人为的规定说,你可以不串数据存储在中间变量,你不能调用外部函数。

This is a purely nonsensical way of doing a swap - the only reason to use this construct is an artificial requirement saying that you can't store string data in intermediate variables and you can't call external functions.

这篇关于是否有可能写的,可以扭转一个字符串不使用缓冲区字符串的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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