c语言实现定长顺序存储,数据结构C语言版串的定长顺序存储表示及实现.doc
时间: 2023-12-03 22:46:29 浏览: 42
很高兴为你解答。C语言实现定长顺序存储串的方法如下:
首先,我们需要定义一个固定长度的字符数组来存储串,如下所示:
```
#define MAXLEN 100 // 定义最大长度
typedef struct {
char data[MAXLEN]; // 存储串的字符数组
int length; // 串的长度
} SqString; // 顺序存储结构体
```
接下来,我们需要实现一些基本操作,如串的初始化、清空、求长度、比较、连接、子串等,具体实现如下:
```
// 初始化串
void InitString(SqString *s, char *str) {
int len = strlen(str);
if (len > MAXLEN) {
len = MAXLEN;
}
for (int i = 0; i < len; i++) {
s->data[i] = str[i];
}
s->length = len;
}
// 清空串
void ClearString(SqString *s) {
s->length = 0;
}
// 求串长度
int Length(SqString s) {
return s.length;
}
// 比较两个串
int StrCompare(SqString s1, SqString s2) {
int len = s1.length < s2.length ? s1.length : s2.length;
for (int i = 0; i < len; i++) {
if (s1.data[i] != s2.data[i]) {
return s1.data[i] - s2.data[i];
}
}
return s1.length - s2.length;
}
// 串连接
void Concat(SqString *s, SqString s1, SqString s2) {
int len = s1.length + s2.length;
if (len > MAXLEN) {
len = MAXLEN;
}
for (int i = 0; i < s1.length; i++) {
s->data[i] = s1.data[i];
}
for (int i = 0; i < s2.length && i < MAXLEN - s1.length; i++) {
s->data[s1.length + i] = s2.data[i];
}
s->length = len;
}
// 取子串
void SubString(SqString *sub, SqString s, int pos, int len) {
if (pos < 1 || pos > s.length || len < 0 || len > s.length - pos + 1) {
return;
}
for (int i = 0; i < len; i++) {
sub->data[i] = s.data[pos + i - 1];
}
sub->length = len;
}
```
通过以上代码,我们便可以实现定长顺序存储串的基本操作。
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)