反向C型字符串? - C ++ [英] Reverse C-style String? - C++

查看:215
本文介绍了反向C型字符串? - C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用指针来反转C ++中的char数组。我想知道是否有什么我应该做不同?我这样做正确吗?有没有更有效的方法来完成这个?



我的小程式:

  int main()
{
char buffer [80];

PrintHeader();

cout<< \\\
String reversal program;
cout<< \\\
Type in a short string of words。;
cout<< \ n我会扭转他们。
cout<< \\\
:;
cin.getline(buffer,79);

cout<< \\\
You typed<<缓冲;
reverse(buffer);
cout<< \\\
Reversed:<<缓冲;

cout<< endl
system(PAUSE);
return 0;

}


void reverse(char * string)
{
char * pStart,* pEnd;
int length;
char temp;

length = strlen(字符串);

pStart = string;
pEnd =& string [length - 1];

while(pStart< pEnd)
{
temp = * pStart;
* pStart = * pEnd;
* pEnd = temp;
pStart ++;
pEnd--;
}
}


解决方案

p> 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());
}


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 ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆