字符串翻转(面试题2)

参考链接地址:http://www.cricode.com/258.html

题目

写代码翻转一个C风格的字符串。(C风格的意思是”abcd”需要用5个字符来表示,包含末尾的 结束字符)

解答

这道题如果就是要考察你有没有注意到C风格字符串最后的那个结束符,那我觉得还是像书 上写的那样,在代码中有所体现。

字符串翻转(面试题2)

全部代码如下:

/*===============================================

# Author: RollerCoaster

# Last modified:2014-09-09 14:27

# Filename: 02字符串翻转.c

# Description: 题目:写代码翻转一个c风格的字符串(c风格)

#   的意思是"abcd"需要用5个字符来表示,包含末尾的结束字符

=================================================*/



#include<iostream>

#include<string>

using namespace std;



// 功能:实现a和b的交换

// 参数:a和b

// 返回:空

void swap(char &a, char &b)

{

    // 异或运算

    // a = 3 = 0011; b = 4 = 0100;

    // a = 0011 ^ 0100 = 0111 = 7

    // b = 0111 ^ 0100 = 0011 = 3

    // a = 0111 ^ 0011 = 0100 = 4

    a = a ^ b;

    b = a ^ b;

    a = a ^ b;

}



// 功能:翻转一个字符创(带结束符)

// 参数:字符串

// 返回:空

void reverse1(char *s)

{

    if (!s)

    {

        return;

    }



    char *p = s;

    char *q = s;

    while(*q)

    {

        ++q;

    }

    --q;

    while(p < q)

    {

        swap(*p++, *q--);

    }

}



// 功能:翻转字符串

// 参数:字符串

// 返回:空

void reverse2(char *s)

{

    int n = strlen(s);

    for(int i = 0; i < n / 2; i++)

    {

        swap(s[i], s[n - i - 1]);

    }

}



int main()

{

    char s[] = "1234567890";

    reverse1(s);

    cout << s << endl;

    return 0;

}

 

你可能感兴趣的:(字符串)