给定字符串s,字符c1和c2。已知c1和c2在s中仅出现一次,并且c1不等于c2。计算c1和c2之间相隔字符的个数。python
时间: 2023-05-15 22:07:20 浏览: 30
可以使用字符串的 find() 方法来找到 c1 和 c2 在字符串 s 中的位置,然后计算它们之间相隔字符的个数。具体代码如下:
s = "hello world"
c1 = "h"
c2 = "d"
pos1 = s.find(c1)
pos2 = s.find(c2)
if pos1 > pos2:
pos1, pos2 = pos2, pos1
count = pos2 - pos1 - 1
print(count)
输出结果为:8
这里假设字符串 s 中只包含 ASCII 字符,如果有 Unicode 字符的话,需要使用更复杂的方法来计算字符之间的距离。
相关问题
给定字符串s,字符c1和c2。已知c1和c2在s中仅出现一次,并且c1不等于c2。计算c1和c2之间相隔字符的个数。
以下是代码实现:
```python
def distance_between_chars(s, c1, c2):
index1 = s.index(c1)
index2 = s.index(c2)
return abs(index1 - index2) - 1
```
这个函数会返回c1和c2之间相隔字符的个数。
给定字符串s字符c1和c2,已知c1和c2在s中仅出现一次,并且c1不等于c2,计算c1和c2之间相隔字符的个数简单python代码
以下是简单的 Python 代码实现:
s = input("请输入字符串s:")
c1 = input("请输入字符c1:")
c2 = input("请输入字符c2:")
# 找到 c1 和 c2 在字符串 s 中的位置
pos1 = s.index(c1)
pos2 = s.index(c2)
# 计算 c1 和 c2 之间相隔字符的个数
distance = abs(pos1 - pos2) - 1
print("c1 和 c2 之间相隔字符的个数为:", distance)