使用字符数组反转字符串

Ayu*_*waj 0 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;
}
Run Code Online (Sandbox Code Playgroud)

一个输出实例是:

Enter the string : asdfgh

 The reversed string is : 
dsa
Run Code Online (Sandbox Code Playgroud)

我想在现场解决这个问题并使用字符数组.

互联网上有许多解决方案.我见过他们.但是我想知道这个实现在哪里出错了.如果str中有一些额外的增量.我想知道如何纠正它.

eri*_*rip 5

我认为你让问题太混乱了.

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 对不起,这不是一个有用的答案.互联网充满了这样的答案. (4认同)