写一个c语言程序,设计顺序串的基本运算程序,并用相关数据进行测试
时间: 2023-04-11 08:01:49 浏览: 119
好的,以下是一个基本的顺序串运算程序的C语言代码:
```c
#include <stdio.h>
#include <string.h>
#define MAXLEN 100
typedef struct {
char data[MAXLEN];
int length;
} SeqString;
void InitString(SeqString *s, char *str) {
int len = strlen(str);
if (len > MAXLEN) {
printf("String too long!\n");
return;
}
strcpy(s->data, str);
s->length = len;
}
void PrintString(SeqString s) {
for (int i = 0; i < s.length; i++) {
printf("%c", s.data[i]);
}
printf("\n");
}
void Concat(SeqString *s1, SeqString s2) {
if (s1->length + s2.length > MAXLEN) {
printf("String too long!\n");
return;
}
for (int i = 0; i < s2.length; i++) {
s1->data[s1->length + i] = s2.data[i];
}
s1->length += s2.length;
}
int SubString(SeqString s, int pos, int len, SeqString *sub) {
if (pos < 1 || pos > s.length || len < 0 || pos + len - 1 > s.length) {
printf("Invalid position or length!\n");
return 0;
}
for (int i = 0; i < len; i++) {
sub->data[i] = s.data[pos + i - 1];
}
sub->length = len;
return 1;
}
int Index(SeqString s, SeqString t) {
int i = 1, j = 1;
while (i <= s.length && j <= t.length) {
if (s.data[i - 1] == t.data[j - 1]) {
i++;
j++;
} else {
i = i - j + 2;
j = 1;
}
}
if (j > t.length) {
return i - t.length;
} else {
return 0;
}
}
int main() {
SeqString s1, s2, sub;
char str1[] = "Hello";
char str2[] = "World";
InitString(&s1, str1);
InitString(&s2, str2);
printf("s1: ");
PrintString(s1);
printf("s2: ");
PrintString(s2);
Concat(&s1, s2);
printf("s1 after concatenation: ");
PrintString(s1);
SubString(s1, 3, 4, &sub);
printf("Substring of s1 from position 3 with length 4: ");
PrintString(sub);
char str3[] = "lo";
SeqString t;
InitString(&t, str3);
int pos = Index(s1, t);
if (pos) {
printf("Substring \"%s\" found in s1 at position %d.\n", str3, pos);
} else {
printf("Substring \"%s\" not found in s1.\n", str3);
}
return 0;
}
```
你可以用任何你想要的字符串来测试这个程序。
阅读全文