c语言字符串比较指针
时间: 2023-11-23 10:51:10 浏览: 116
比较字符串的指针应该使用strcmp函数来实现。strcmp函数比较两个字符串的大小,如果字符串相同则返回0,如果第一个字符串小于第二个字符串则返回一个负数,如果第一个字符串大于第二个字符串则返回一个正数。以下是一个示例代码:
#include <stdio.h>
#include <string.h>
int main() {
char arr1[] = "abcdef";
char arr2[] = "abc";
int result = strcmp(arr1, arr2);
if (result < 0) {
printf("arr1 < arr2\n");
} else if (result > 0) {
printf("arr1 > arr2\n");
} else {
printf("arr1 = arr2\n");
}
return 0;
}
相关问题
c语言字符串替换指针
以下是一个使用指针进行C语言字符串替换的示例代码:
```c
#include <stdio.h>
#include <string.h>
void replace(char *str, char *orig, char *rep)
{
static char buffer[4096];
char *p;
if(!(p = strstr(str, orig))) // 在str中查找orig
return;
strncpy(buffer, str, p-str); // 复制p之前的部分到buffer中
buffer[p-str] = '\0';
sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig)); // 将rep和p之后的部分连接到buffer中
strcpy(str, buffer); // 将buffer复制回str中
replace(str, orig, rep); // 递归调用,继续查找并替换
}
int main()
{
char str[] = "hello world, world!";
char orig[] = "world";
char rep[] = "earth";
replace(str, orig, rep);
printf("%s\n", str); // 输出:hello earth, earth!
return 0;
}
```
该示例代码中,`replace`函数使用指针实现了字符串替换功能。它首先在`str`中查找`orig`,如果找到了,就将`orig`替换为`rep`。然后,它使用递归调用,继续查找并替换,直到`str`中不再包含`orig`为止。
C语言字符串排序指针Malloc
以下是使用指针和动态内存分配(malloc)对字符串进行排序的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sortStrings(char **str, int n);
int main() {
int n, i;
char **str;
printf("请输入字符串的个数:");
scanf("%d", &n);
// 动态分配内存
str = (char **) malloc(n * sizeof(char *));
for (i = 0; i < n; i++) {
str[i] = (char *) malloc(100 * sizeof(char));
printf("请输入第%d个字符串:", i + 1);
scanf("%s", str[i]);
}
// 对字符串进行排序
sortStrings(str, n);
// 输出排序后的字符串
printf("排序后的字符串为:\n");
for (i = 0; i < n; i++) {
printf("%s\n", str[i]);
}
// 释放内存
for (i = 0; i < n; i++) {
free(str[i]);
}
free(str);
return 0;
}
void sortStrings(char **str, int n) {
int i, j;
char *temp;
// 选择排序
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (strcmp(str[i], str[j]) > 0) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)