字符串比较:输入两个字符串str1和str2,编程实现比较两个字符串的大小。当字符串str1>str2时,输出1;当字符串str1=str2时,输出0;当字符串str1<str2时,输出-1。
时间: 2023-12-03 10:42:51 浏览: 27
以下是一个简单的实现方式,基于字符串的比较原理,逐个字符比较,如果字符相等则比较下一个字符,如果字符不相等,则返回它们的 ASCII 码的差值。
```python
def compare_strings(str1, str2):
n1 = len(str1)
n2 = len(str2)
i = 0
while i < n1 and i < n2:
if str1[i] == str2[i]:
i += 1
continue
else:
return ord(str1[i]) - ord(str2[i])
if n1 == n2:
return 0
elif n1 > n2:
return 1
else:
return -1
```
其中,`ord()` 函数返回一个字符的 ASCII 码值。
相关问题
C语言:输入两个字符串str1和str2,输出str2在str1中的所有位置,没有则输出no
以下是一个基于C语言的实现,可以实现输入两个字符串str1和str2,输出str2在str1中的所有位置,没有则输出no:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
printf("请输入字符串1:");
scanf("%s", str1);
printf("请输入字符串2:");
scanf("%s", str2);
int len1 = strlen(str1), len2 = strlen(str2);
int i, j, k, flag;
for (i = 0; i <= len1 - len2; i++) {
flag = 1;
for (j = 0, k = i; j < len2; j++, k++) {
if (str2[j] != str1[k]) {
flag = 0;
break;
}
}
if (flag) {
printf("在位置%d处发现字符串2\n", i);
}
}
if (!flag) {
printf("no\n");
}
return 0;
}
```
该程序首先使用`scanf`函数分别读入两个字符串`str1`和`str2`,然后使用`strlen`函数求出两个字符串的长度。接着,使用两个循环嵌套来枚举`str2`在`str1`中出现的位置,具体地,外层循环控制`str2`在`str1`中的起始位置,内层循环则用于比较`str1`和`str2`中对应位置的字符是否相同。如果在某个位置发现`str2`,则输出该位置。最后,如果没有发现`str2`,则输出`no`。
输入两个字符串str1和str2,查找str2在str1里首次出现的位置
可以使用Python中的字符串查找函数find()来实现:
```
str1 = input("请输入字符串1:")
str2 = input("请输入字符串2:")
index = str1.find(str2)
if index == -1:
print("字符串2在字符串1中不存在")
else:
print("字符串2在字符串1中第一次出现的位置为:", index)
```
运行结果示例:
```
请输入字符串1:hello world
请输入字符串2:world
字符串2在字符串1中第一次出现的位置为: 6
```
相关推荐
![](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)