为了在C/C++编程环境中实现通过指针交换两个数据的要求,特编写此程序
为方便演示,本文的数据为从控制台输入的一个字符串,并将其拆分为两个子串
分析:
- 首先接收控制台输入的字符串,输入时要求用空格分开两个子串
- 对输入的字符串进行处理,得到两个子串,并定义两个字符型指针指向这两个子串
- 通过指针依次打印两个子串
- 方法1:直接在主函数中交换两个字符串指针
- 方法2:定义一个交换函数,使用二级指针交换两个指针(因为此时指针变量的作用域发生变化,所以要用二级指针来交换一级指针)
- 通过指针再次打印两个子串,发现顺序已经发生变化
代码如下:
// in: Chen Lin Yu 123
// out: 123 Chen Lin Yu
#include <iostream>
#include <string.h>
using namespace std;
#define BUFFER 50
void exchange(char **pt_name, char **pt_number)
{
char *pt_temp = NULL;
pt_temp = *pt_name;
*pt_name = *pt_number;
*pt_number = pt_temp;
}
int main()
{
char name[20] = {0};
char number[20] = {0};
char input_str[BUFFER] = {0};
char *pt_name = name;
char *pt_number = number;
int len = 0;
int idx_name = 0;
int idx_number = 0;
int seg_index = 0;
cout << "please input name and number, then press enter" << endl;
cin.get(input_str, BUFFER);
cout << "input: " << input_str << endl;
len = strlen(input_str);
for (int i = len - 1; i >= 0; i--) {
if (input_str[i] == ' ') {
seg_index = i;
break;
}
}
for (int i = 0; i < seg_index; i++) {
name[idx_name] = input_str[i];
idx_name ++;
}
for (int i = seg_index + 1; i < len; i++) {
number[idx_number] = input_str[i];
idx_number ++;
}
cout << "before exchange: " << pt_name << " " <<pt_number << endl;
// way1: direct exchange
// char *pt_temp = NULL;
// pt_temp = name;
// pt_name = pt_number;
// pt_number = pt_temp;
// way2: function exchange
exchange(&pt_name, &pt_number);
cout << "after exchange: "<< pt_name << " " <<pt_number << endl;
return 0;
}
运行结果如下:
总结:本文重点复习了通过指针交换数据的用法,特别是通过函数交换指针时,函数参数一定要使用二级指针,调用该函数时,传入要交换指针的地址。此外,本文对字符串的分隔为两个子串进行了处理,其方法为从后遍历,直到遇到空格,此时的索引号即将原字符串分隔为两个子串