我想在 C++ 中使用指针来反转 char 数组。我想知道是否有什么我应该做的不同的事情?我这样做正确吗?有没有更有效的方法来完成这个?
我的小程序:
int main ( )
{
char buffer[80];
PrintHeader();
cout << "\nString reversal program";
cout << "\nType in a short string of words.";
cout << "\nI will reverse them.";
cout << "\n:";
cin.getline(buffer, 79);
cout << "\nYou typed " << buffer;
reverse (buffer);
cout << "\nReversed: " << buffer;
cout << endl;
system("PAUSE");
return 0;
}
void reverse(char* string)
{
char* pStart, *pEnd;
int length;
char temp;
length = strlen(string);
pStart = string;
pEnd = &string[length - 1];
while(pStart < pEnd)
{
temp = *pStart;
*pStart = *pEnd;
*pEnd = temp;
pStart++;
pEnd--;
}
}
最佳答案
void str_reverse( char *str ) {
char *str_end = strchr( str, 0 );
std::reverse( str, str_end );
}
如果你要写一个循环,
void str_reverse( char *str ) {
std::size_t len = std::strlen( str );
for ( std::size_t index = 0; index != len / 2; ++ index ) {
std::swap( str[ index ], str[ len - index - 1 ] );
}
}
或者,当然,如果您可以使用 C++ 字符串,
void str_reverse( std::string &str ) {
std::reverse( str.begin(), str.end() );
}
关于c++ - 反向 C 风格的字符串? - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2197412/