C语言指针交换两个字符串的函数
时间: 2024-05-09 10:20:50 浏览: 9
好的,这是一个用 C 语言实现的交换两个字符串的函数:
```
#include <stdio.h>
#include <string.h>
void swap_strings(char **str1, char **str2) {
char *temp = *str1;
*str1 = *str2;
*str2 = temp;
}
int main() {
char *str1 = "hello";
char *str2 = "world";
swap_strings(&str1, &str2);
printf("str1 is now %s\n", str1);
printf("str2 is now %s\n", str2);
return 0;
}
```
这个函数接受两个参数:指向字符串的指针,然后使用一个临时变量来交换这两个字符串。
相关问题
c语言指针,两个字符串拼接
在 C 语言中,可以使用指针和字符串处理函数来实现字符串的拼接。以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello, ";
char str2[20] = "world!";
// 使用 strcat 函数将 str2 拼接到 str1 的结尾
strcat(str1, str2);
printf("%s\n", str1); // 输出拼接后的字符串
return 0;
}
```
在上面的代码中,我们首先定义了两个字符串 `str1` 和 `str2`,并初始化了 `str1`。然后,我们使用 `strcat()` 函数将 `str2` 拼接到 `str1` 的结尾。最后,我们使用 `printf()` 函数输出拼接后的字符串。
输出结果为:
```
Hello, world!
```
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`函数将第一个字符串复制到一个临时数组中,然后将第二个字符串复制到第一个字符串中,最后将临时数组中的字符串复制到第二个字符串中。