我写了一个程序来反转字符串,其中字符串是一个字符数组。程序是:
#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/