#include<iostream>
using namespace std;
const int tsize = 10;
struct str
{
int length;
int time;
int maxsize;
char *a;
};
void initial(str &n);
void input(str &n);
void extend(str &n);
int index(str &n, str &m);
void length(str &n);
void output(str n);
int main()
{
cin >> noskipws;
str a, b;
initial(a);
initial(b);
input(a);
input(b);
length(b);
output(b);
// index(a,b);
}
void initial(str &n)
{
n.time = 1;
n.maxsize = tsize;
n.a = new char[tsize];
}
void input(str &n)
{
cout << "输入字符串" << endl;
char a = '\0';
int i;
for (i = 1; true; i++)
{
cin >> a;
if (a == '#')
{
cout << "输入结束" << endl;
break;
}
else
{
if (i >= n.maxsize) // i也表示串的长度,当该次需存储的内
//容大于最大空间,必须开辟空间,否则无法存储
{
n.length = i - 1;
cout << "当延长时,串长度为: " << n.length << endl;
extend(n);
}
n.a[i] = a;
}
}
n.length = i - 1;
}
void extend(str &n) //作用相当于 realloc
{
n.time++;
char *temp = new char[n.time*tsize];
n.maxsize = (n.time)*tsize;
for (int i = 1; i <= n.length; i++)
{
temp[i] = n.a[i]; //
}
delete[]n.a;
n.a = temp;
}
int index(str &n, str &m) //n 为主串,m 为模式串
{
int i = 1; //i 用于主串遍历
int j = 1; //j 用于模式串遍历
int k = i; //k 用于在匹配时在主串上移动
while (j <= m.length && k <= n.length)
{
if (n.a[k] == m.a[j])
{
j++;
k++;
}
else
{
j = 1;
i++;
k = i;
}
}
if (j >= m.length + 1)
{
cout << i << endl;
return 0;
}
else
{
cout << "匹配失败" << endl;
return 0;
}
}
void length(str &n)
{
cout << "字符串长为: " << n.length << endl;
}
void output(str n)
{
int i = 1;
for (; i <= n.length; i++)
{
cout << n.a[i];
}
cout << endl;
}
第一个字符串没有问题,第二个字符串头起多了一个回车。
后边的index 匹配函数里 b串中的每一个字符都是回车。
希望对您有帮助:https://blog.csdn.net/it_xiangqiang/category_10581430.html
希望对您有帮助:https://blog.csdn.net/it_xiangqiang/category_10768339.html