c++引用传递交换字符串
时间: 2023-12-05 07:02:05 浏览: 65
在 C 语言中,可以通过指针和引用传递来交换字符串。下面是一个使用指针传递的代码示例:
```c
#include <stdio.h>
void swap(char **str1, char **str2) {
char *temp = *str1;
*str1 = *str2;
*str2 = temp;
}
int main() {
char *str1 = "Hello";
char *str2 = "World";
printf("Before swapping: str1 = %s, str2 = %s\n", str1, str2);
swap(&str1, &str2);
printf("After swapping: str1 = %s, str2 = %s\n", str1, str2);
return 0;
}
```
输出:
```
Before swapping: str1 = Hello, str2 = World
After swapping: str1 = World, str2 = Hello
```
在这个示例中,`swap()` 函数使用指向指针的指针,即 `char **` 类型的参数。然后,它通过交换指针的值来交换字符串。在 `main()` 函数中,我们传递了 `str1` 和 `str2` 的地址,以便在 `swap()` 函数中进行修改。
同样,我们也可以使用引用传递来交换字符串。下面是一个使用引用传递的代码示例:
```c
#include <stdio.h>
void swap(char *&str1, char *&str2) {
char *temp = str1;
str1 = str2;
str2 = temp;
}
int main() {
char *str1 = "Hello";
char *str2 = "World";
printf("Before swapping: str1 = %s, str2 = %s\n", str1, str2);
swap(str1, str2);
printf("After swapping: str1 = %s, str2 = %s\n", str1, str2);
return 0;
}
```
输出:
```
Before swapping: str1 = Hello, str2 = World
After swapping: str1 = World, str2 = Hello
```
在这个示例中,`swap()` 函数使用引用参数,即 `char *&` 类型的参数。然后,它通过交换指针的值来交换字符串。在 `main()` 函数中,我们直接传递 `str1` 和 `str2` 的引用,以便在 `swap()` 函数中进行修改。