C++串-顺序存储

SeqString.h

1
2
3
4
5
6
7
8
9
10
11
12
13
#pragma once
#include<iostream>
using namespace std;
#define MAXSIZE 100
class SeqString
{
private:
char data[MAXSIZE];
public:
SeqString(const char* s);
int Length();
int Find( SeqString& s,int sc= 0);
};

SeqString.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include "SeqString.h"

SeqString::SeqString(const char* s)
{
int i = 0;
for (; s[i] != 0; i++)
data[i] = s[i];
data[i] = 0;
}

int SeqString::Length()
{
int n = 0;
for (size_t i = 0; data[i]!=0; i++)
{
n++;
}
return n;
}

int SeqString::Find(SeqString& s,int sc)
{
int i = sc, j = 0;
while (data[i] != 0 && s.data[j] != 0)
{
if (data[i] == s.data[j])
i++, j++;
else
i = i - j + 1, j = 0;
}
if (s.data[j] == 0)
return i - j;
else
return -1;
}

main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
using namespace std;
#include"SeqString.h"

int main()
{
SeqString str("IlikecIlikecIlikec");
SeqString t("like");
cout << str.Length() << endl;

int k = str.Find(t);

while (k != -1)
{
cout << k << endl;
k = str.Find(t, t.Length() + k);
}

return 0;
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!