用c语言交换两个字符
时间: 2024-02-26 18:57:02 浏览: 41
可以使用一个临时变量来交换两个字符的值,具体代码如下:
```c
#include <stdio.h>
int main() {
char a = 'a';
char b = 'b';
char temp;
printf("Before swapping: a = %c, b = %c\n", a, b);
temp = a;
a = b;
b = temp;
printf("After swapping: a = %c, b = %c\n", a, b);
return 0;
}
```
输出结果为:
```
Before swapping: a = a, b = b
After swapping: a = b, b = a
```
相关问题
C语言如何交换两个字符串
在C语言中,交换两个字符串可以通过以下代码实现:
```c
#include <stdio.h>
#include <string.h>
void swap(char *str1, char *str2) {
char temp[strlen(str1) + 1];
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
}
int main() {
char str1[100], str2[100];
printf("Enter string 1: ");
scanf("%s", str1);
printf("Enter string 2: ");
scanf("%s", str2);
printf("Before swapping, string 1: %s, string 2: %s\n", str1, str2);
swap(str1, str2);
printf("After swapping, string 1: %s, string 2: %s\n", str1, str2);
return 0;
}
```
在这个代码中,`swap`函数接收两个字符指针作为参数,使用`strcpy`函数将第一个字符串复制到一个临时数组中,然后将第二个字符串复制到第一个字符串中,最后将临时数组中的字符串复制到第二个字符串中。
C语言:两个字符串交换的函数
以下是用C语言编写的两个字符串交换函数的不同方式:
方法一:使用临时变量
```c
void swap(char *str1, char *str2) {
char temp[100]; // 声明一个临时数组
strcpy(temp, str1); // 将 str1 复制到 temp 中
strcpy(str1, str2); // 将 str2 复制到 str1 中
strcpy(str2, temp); // 将 temp 复制到 str2 中
}
```
方法二:不使用临时变量
```c
void swap(char *str1, char *str2) {
// 使用异或运算交换两个字符串
int i;
for (i = 0; str1[i] != '\0' && str2[i] != '\0'; i++) {
str1[i] ^= str2[i];
str2[i] ^= str1[i];
str1[i] ^= str2[i];
}
// 如果两个字符串长度不同,则将其中较长的字符串剩余部分复制到另一个字符串中
if (str1[i] != '\0' || str2[i] != '\0') {
strcat(str1, str2);
strcpy(str2, str1 + i);
str1[i] = '\0';
}
}
```
这两个函数都接受两个指向字符串的指针作为参数,并将这两个字符串交换。第一个函数使用了一个临时数组来交换两个字符串,而第二个函数则使用了异或运算来进行交换,并处理了两个字符串长度不同的情况。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)