数据结构_串_串的一些操作_C++实现
head.h
#include<iostream>
#include<string>
using namespace std;
class STRING
{
public:
STRING();
void GetString();
void GetSubString();
void Index();
void Print();
private:
void Index1();
void Index2();
bool Match(int);
string str;
string sub;
int strlen;
int sublen;
int pos;
};
STRING::STRING()
{
str.clear();
sub.clear();
pos = strlen = sublen = 0;
}
void STRING::GetString()
{
cout << "Please Input The MainString :" << endl << endl;
cin >> str;
strlen = str.length();
}
void STRING::GetSubString()
{
cout << "Please Input The SubString :" << endl << endl;
cin >> sub;
sublen = sub.length();
}
void STRING::Index()
{
cout << "Index Called !" << endl << endl;
cout << "Which Position Do You Want To Start Your Index ?" << endl << endl;
cin >> pos;
pos--;
cout << "Which Method Do You Want To Use ?" << endl << endl;
cout << "1 . Simple Method ." << endl << "2 . Improvement Method ." << endl
<< endl;
char choice;
cin >> choice;
switch (choice)
{
case '1':
Index1();
break;
case '2':
Index2();
break;
default:
cout << "No Such Method !" << endl << endl;
break;
}
}
void STRING::Index1()
{
cout << "Simple Method Called !" << endl << endl;
if (pos > strlen - sublen)
{
cout << "Failed !" << endl << endl;
return;
}
int i, j;
i = pos;
j = 0;
while (i < strlen && j < sublen)
{
if (str[i] == sub[j])
{
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
if (j == sublen)
{
cout << "Succed ! " << " Position = " << i - j + 1 << endl << endl;
}
else
{
cout << "Failed !" << endl << endl;
}
}
void STRING::Index2()
{
cout << "ImproveMent Method Called !" << endl << endl;
int i, j;
i = pos;
j = 0;
while (i <= strlen - sublen && j < sublen)
{
if (str[i] == sub[j] && str[i + sublen - 1] == sub[sublen - 1]
&& Match(i))
{
cout << "Succed ! " << " Position = " << i - j + 1 << endl << endl;
return;
}
else
{
i++;
j = 0;
}
}
cout << "Failed !" << endl << endl;
}
void STRING::Print()
{
cout << "Main String = " << str << endl << " Length = " << strlen << endl;
cout << "SubString = " << sub << endl << " Length = " << sublen << endl
<< endl;
}
bool STRING::Match(int i)
{
for (int j = 0; j < sublen; j++)
{
if (str[i + j] != sub[j])
return false;
}
return true;
}
main.cpp
#include<iostream>
#include"head.h"
using namespace std;
int main()
{
STRING str;
char choice;
while (1)
{
cout << "Your Choice Please ?" << endl << endl << "1 . Set Main String"
<< endl << "2 . Set SubString" << endl << "3 . Index" << endl
<< "4 . Print" << endl << "5 . Quit" << endl << endl;
cin >> choice;
switch (choice)
{
case '1':
str.GetString();
break;
case '2':
str.GetSubString();
break;
case '3':
str.Index();
break;
case '4':
str.Print();
break;
case '5':
return 0;
default:
cout << "No Such Choice !" << endl;
break;
}
}
}