使用顺序结构存储字符串,完成字符串基本操作:如初始化、求长度、字符串连接等
时间: 2024-02-02 22:02:34 浏览: 38
以下是使用顺序结构存储字符串的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct {
char data[MAX_SIZE];
int length;
} SeqString;
// 初始化字符串
void InitString(SeqString *s, char *str) {
int len = strlen(str);
if (len > MAX_SIZE) {
printf("Error: string too long!\n");
exit(1);
}
strcpy(s->data, str);
s->length = len;
}
// 求字符串长度
int Length(SeqString *s) {
return s->length;
}
// 字符串连接
void Concat(SeqString *s1, SeqString *s2, SeqString *result) {
if (s1->length + s2->length > MAX_SIZE) {
printf("Error: string too long!\n");
exit(1);
}
strcpy(result->data, s1->data);
strcat(result->data, s2->data);
result->length = s1->length + s2->length;
}
int main() {
SeqString s1, s2, result;
char str1[] = "Hello";
char str2[] = "World";
InitString(&s1, str1);
InitString(&s2, str2);
printf("s1: %s, length: %d\n", s1.data, Length(&s1));
printf("s2: %s, length: %d\n", s2.data, Length(&s2));
Concat(&s1, &s2, &result);
printf("result: %s, length: %d\n", result.data, Length(&result));
return 0;
}
```
在上述代码中,我们定义了一个 `SeqString` 结构体表示顺序存储的字符串,其中包含一个字符数组 `data` 和一个整型 `length`,分别表示字符串的内容和长度。接下来,我们可以使用 `InitString` 函数初始化字符串,使用 `Length` 函数求字符串长度,使用 `Concat` 函数连接两个字符串。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)