如何交换两个字符串

#include 
using namespace std;

void swap(char *&x, char *&y)
{
    char *temp;
    temp = x;
    x = y;
    y = temp;
}

int main()
{
    char *ap = "hello";
    char *bp = "how are you?";

    cout << "ap = " << ap << endl;
    cout << "bp = " << bp << endl;

    swap(ap, bp);

    cout << "swap ap, bp" << endl;
    cout << "ap = " << ap << endl;
    cout << "bp = " << bp << endl;

    return 0;
}

这里swap函数是利用传指针引用实现字符串交换的。由于swap函数是指针引用类型,因此传入的函数就是实参,而不是形参。

如果不用指针引用,那么指针交换只能在swap函数中有效,因为在函数体中,函数栈会分配两个临时的指针变量分别指向两个指针参数。对实际的ap和bp没有影响。

结果:

ap = hello
bp = how are you?
swap ap, bp
ap = how are you?
bp = hello

你可能感兴趣的:(C++面试,c++)