c++ - 使用字符数组反转字符串

标签 c++ arrays string pointers

我写了一个程序来反转字符串,其中字符串是一个字符数组。程序是:

#include<iostream>
void rev(char *str)
{
  char *end;
  end = str;// end will now point to the same address of str
  // now we need to incremet the end pointer upto it encounter null
  if(str)// this checks if the string is present or not
  {
    while(*end)
      ++end;
    --end;// set one character back, since last character is null
    // swap characters from start of string with the end of the string
    // until the pointers meet in middle.
    while(str < end)
    {
      char temp = *str;
      *str++ = *end;
      *end-- = temp;
    }
  }
  std::cout<<"\n The reversed string is : \n";
  std::cout<<str<<std::endl;
}
int main()
{
  char str[500];
  std::cout<<"\n Enter the string : ";
  std::cin.getline(str, sizeof(str));
  rev(str);
  return 0;
}

一个输出实例是:

Enter the string : asdfgh

 The reversed string is : 
dsa

我想就地解决这个问题并使用字符数组。

Internet 上有许多可用的解决方案。我见过他们。但是我想知道这个实现哪里出了问题。如果 str 中有一些额外的增量。我想知道如何纠正它。

最佳答案

我认为你把问题弄得太困惑了。

void reverse(char* s) {
  // return if s is nullptr
  if(!s) return;

  size_t len = strlen(s);

  // swap ith from front with ith from back
  for(size_t i = 0; i < len/2; ++i) {
    char temp = s[i];
    s[i] = s[len - i - 1];
    s[len - i - 1] = temp;
  }
}

关于c++ - 使用字符数组反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35804237/

相关文章:

c++ - 为什么这个函数指针赋值在直接赋值而不是使用条件运算符时起作用?

java - Java中显示数组最后一个元素的条件

vb.net - 如何查找字符串中子字符串的出现次数 vb.net

c++ - 数组成员配对的一般公式?

c++ - 发射信号不更新 GUI 中的值

javascript - 任何人都可以看到这个 javascript 代码中的错误吗?填充二维数组

python - 将样本从 .get_array_of_samples() 转换回 AudioSegment

Java:将十六进制编码的字符串转换为十六进制字节

Php-从数字中删除文本单元

c++ - Clang 格式用撇号打破了大数字的分隔