本文介绍了反向C风格的字符串? - C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用指针来扭转字符数组在C ++中。我在想,如果有什么是我应该做不同?我在做正确吗?有没有做到这一点更有效的方式?
我的小程序:
INT的main()
{
字符缓冲区[80]; PrintHeader(); COUT<< \\ nString逆转节目;
COUT<< 在字的短字符串\\ n类型。
COUT<< \\ NI将扭转他们。
COUT<< \\ n;
cin.getline(缓冲液,79); COUT<< \\ n你输入<<缓冲;
反向(缓冲液);
COUT<< \\ nReversed:&所述;&下;缓冲; COUT<< ENDL;
系统(暂停);
返回0;}
void反转(字符*字符串)
{
字符* PSTART,*挂起;
INT长;
焦温度; 长度= strlen的(字符串); PSTART =串;
小彭=放大器;字符串[长度 - 1]; 而(PSTART<小彭)
{
TEMP = * PSTART;
* PSTART = *挂起;
*小彭=温度;
PSTART ++;
pEnd--;
}
}
解决方案
无效str_reverse(字符* STR){
字符* str_end =和strchr(STR,0);
的std ::反转(STR,str_end);
}
如果你应该写一个循环,
无效str_reverse(字符* STR){
的std ::为size_t的len =的std :: strlen的(STR);
对于(的std ::为size_t指数= 0;指数= len个/ 2;!++指数){
的std ::互换(STR [指数],海峡[长度 - 指数 - 1]);
}
}
或者,当然,如果你能使用C ++字符串,
无效str_reverse(标准::字符串&安培; STR){
性病::扭转(str.begin(),str.end());
}
I want to use pointers to reverse a char array in C++. I was wondering if there is anything that I should do differently? Am I doing this correctly? Is there a more efficient way to accomplish this?
My small program:
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 );
}
if you're supposed to write a loop,
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 ] );
}
}
or, of course, if you can use a C++ string,
void str_reverse( std::string &str ) {
std::reverse( str.begin(), str.end() );
}
这篇关于反向C风格的字符串? - C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!