写一个C 语言 字符串比较程序
时间: 2024-05-11 20:18:57 浏览: 31
以下是一个简单的C语言字符串比较程序:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
int result;
printf("输入第一个字符串: ");
fgets(str1, sizeof(str1), stdin);
printf("输入第二个字符串: ");
fgets(str2, sizeof(str2), stdin);
result = strcmp(str1, str2);
if (result == 0) {
printf("两个字符串相同\n");
} else {
printf("两个字符串不同\n");
}
return 0;
}
```
该程序首先要求用户输入两个字符串,然后使用 `strcmp()` 函数比较它们。如果两个字符串相同,则输出“两个字符串相同”,否则输出“两个字符串不同”。
相关问题
用c语言写一个计算字符串距离的程序
字符串距离是指将一个字符串转换为另一个字符串所需的最少操作次数,其中操作包括插入、删除和替换字符。可以使用动态规划来解决这个问题,下面是一份 C 语言实现的示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 1000
int min(int x, int y, int z) {
if (x < y && x < z) {
return x;
} else if (y < x && y < z) {
return y;
} else {
return z;
}
}
int string_distance(char* str1, char* str2) {
int len1 = strlen(str1);
int len2 = strlen(str2);
int dp[MAX_LEN][MAX_LEN];
for (int i = 0; i <= len1; i++) {
dp[i][0] = i;
}
for (int j = 0; j <= len2; j++) {
dp[0][j] = j;
}
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
if (str1[i-1] == str2[j-1]) {
dp[i][j] = dp[i-1][j-1];
} else {
dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]);
}
}
}
return dp[len1][len2];
}
int main() {
char str1[MAX_LEN], str2[MAX_LEN];
printf("请输入两个字符串:\n");
scanf("%s%s", str1, str2);
int distance = string_distance(str1, str2);
printf("字符串距离为:%d\n", distance);
return 0;
}
```
在这个程序中,我们首先定义了一个 `min` 函数,用于求三个数中的最小值。然后我们定义了一个 `string_distance` 函数,该函数接受两个字符串作为参数,返回它们之间的字符串距离。在函数内部,我们使用了一个二维数组 `dp` 来记录状态转移过程,其中 `dp[i][j]` 表示将字符串 `str1` 的前 `i` 个字符转换为字符串 `str2` 的前 `j` 个字符所需的最少操作次数。最后,我们在 `main` 函数中读入两个字符串,并调用 `string_distance` 函数来计算它们之间的字符串距离,并输出结果。
帮我写一个C语言程序比较三个字符串大小
好的,以下是一个比较三个字符串大小的 C 语言程序:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], str3[100];
printf("请输入三个字符串:\n");
scanf("%s %s %s", str1, str2, str3);
if (strcmp(str1, str2) > ) {
if (strcmp(str1, str3) > ) {
printf("%s 最大\n", str1);
} else {
printf("%s 最大\n", str3);
}
} else {
if (strcmp(str2, str3) > ) {
printf("%s 最大\n", str2);
} else {
printf("%s 最大\n", str3);
}
}
return ;
}
```
希望能够帮到您!