张庆 集美大学 实验9 串的基本操作 顺序串基本操作
时间: 2025-06-23 19:28:12 浏览: 0
### 关于串的基本操作及顺序串基本操作
#### 串的基本概念
串是一种特殊的线性表,其数据元素仅由字符组成。对于串的操作主要包括创建、销毁、赋值、连接、求子串、定位子串等。
#### 创建与销毁字符串
在 Python 中可以轻松地通过简单的赋值语句来创建字符串对象,并不需要显式的创建函数;而由于 Python 的垃圾回收机制自动管理内存空间,因此也无需手动销毁字符串对象[^1]。
```python
s = "这是一个测试字符串"
print(s)
```
#### 赋值操作
可以通过直接给变量名赋予一个新的字符串值完成串的复制或修改已有串的内容:
```python
str_a = "原始字符串"
str_b = str_a # 将 str_a 复制给 str_b
print(f"str_b: {str_b}")
```
#### 连接两个字符串
利用 `+` 或者 `.join()` 方法可实现多个字符串之间的拼接:
```python
part_one = "前半部分"
part_two = "后半部分"
combined_str = part_one + "-" + part_two
print(combined_str)
# 使用 join() 方法
joined_str = "-".join([part_one, part_two])
print(joined_str)
```
#### 获取子串位置 (模式匹配)
Python 提供了内置方法如 `find`, `index` 来查找指定子串的位置。如果找不到则返回 `-1` 或抛出异常。
```python
main_string = "hello world hello python"
sub_string = "world"
position_find = main_string.find(sub_string)
if position_find != -1:
print(f"'{sub_string}' found at index {position_find}")
try:
position_index = main_string.index(sub_string)
except ValueError as e:
print(e)
else:
print(f"'{sub_string}' found at index {position_index}")
```
#### 替换子串
使用 `replace(old, new[, count])` 函数可以在整个字符串中替换所有的旧子串为新子串,也可以设置最大替换次数。
```python
text = "aa bb cc aa dd ee ff gg hh ii jj kk ll mm nn oo pp qq rr ss tt uu vv ww xx yy zz"
new_text = text.replace('bb', 'XX')
limited_replace = text.replace('aa', 'YY', 1) # 只替换成一次
print(new_text)
print(limited_replace)
```
#### 字符串长度计算
获取字符串中的字符数量非常简单,只需要调用内建函数 `len()` 即可得到结果。
```python
sample_str = "example string to measure length"
length_of_sample = len(sample_str)
print(length_of_sample)
```
#### 遍历字符串
遍历字符串的方式有两种:一种是基于索引访问单个字符,另一种则是直接迭代每一个字符。
```python
for i in range(len(sample_str)):
char_at_i = sample_str[i]
print(char_at_i, end=' ')
print("\n")
for character in sample_str:
print(character, end=' ')
```
#### 判断是否为空串
判断一个字符串是不是空串可以直接比较该字符串是否等于空字符串 `""`.
```python
empty_check = ""
non_empty_check = "not empty"
is_empty = not bool(empty_check.strip())
has_content = bool(non_empty_check.strip())
print(is_empty)
print(has_content)
```
#### 顺序串的概念及其特点
顺序串是指采用数组结构存储的一维字符序列,在计算机内部按照连续地址存放各个字符单元。这种表示方式具有存取速度快的优点,但是当涉及到频繁插入删除时效率较低。
#### 基本操作示例代码
下面给出几个常见的顺序串处理例子,包括初始化、清空、追加、截断等功能。
##### 初始化顺序串
定义一个固定大小的最大容量 N 并分配相应大小的空间用于保存实际的数据成员 data 和记录当前有效长度 size 成员。
```c++
#define MAX_SIZE 256
struct SeqString {
int size;
char data[MAX_SIZE];
};
SeqString seqStr; // 定义了一个名为seqStr的对象
```
##### 清空顺序串
将顺序串的有效长度重置为零即可认为完成了清除工作。
```cpp
void clear(SeqString &ss){
ss.size = 0;
}
clear(seqStr);
```
##### 向顺序串末尾添加新的字符
先检查是否有足够的剩余空间容纳新增加的部分,再执行具体的写入动作并更新size属性。
```cpp
bool appendChar(SeqString &ss,char ch){
if(ss.size >= MAX_SIZE-1)return false;
ss.data[ss.size++] = ch;
return true;
}
appendChar(seqStr,'A');
```
##### 删除最后一个字符
只需减少size计数器便能逻辑上移除最后一位字符。
```cpp
void removeLastChar(SeqString &ss){
if(!isEmpty(ss)) --ss.size;
}
removeLastChar(seqStr);
```
阅读全文
相关推荐




