编写程序实现字符串的基本操作,包括求串长、赋值、比较、串连接、求子串、定位和替换算法。</span>
时间: 2023-10-20 22:23:14 浏览: 82
字符串的基本操作的实现
以下是Python语言的实现:
1. 求串长
```python
def strlen(s):
return len(s)
```
2. 赋值
```python
def strassign(s):
return s
```
3. 比较
```python
def strcmp(s1, s2):
if s1 == s2:
return 0
elif s1 < s2:
return -1
else:
return 1
```
4. 串连接
```python
def strcat(s1, s2):
return s1 + s2
```
5. 求子串
```python
def substr(s, pos, length):
return s[pos:pos+length]
```
6. 定位
```python
def strpos(s, target):
return s.find(target)
```
7. 替换
```python
def strreplace(s, old, new):
return s.replace(old, new)
```
示例:
```python
s = "hello world"
print(strlen(s)) # 11
s1 = strassign(s)
print(s1) # hello world
s2 = "world"
print(strcmp(s1, s2)) # 1
s3 = " python"
print(strcat(s1, s3)) # hello world python
print(substr(s1, 0, 5)) # hello
print(strpos(s1, "world")) # 6
print(strreplace(s1, "world", "python")) # hello python
```
阅读全文