#include<iostream>
#define MaxSize 200
using namespace std;
typedef struct
{
char data[MaxSize];
int length;
}SqString;
void StAssign(SqString& s, char data[])//string creation(字符串的建立)
{
int i = 0;
for (; data[i] != '\0'; ++i)
s.data[i] = data[i];
s.length = i;
cout << "字符串建立成功,结果如下" << endl;
cout << "长度为:" << s.length << " ";
for (int i = 0; i < s.length; ++i)
{
cout << s.data[i];
}
cout << endl;
}
void InsStr(SqString& s1, SqString& s2,SqString &s3, int i)
{
if (i<0 || i>s1.length)
{
cout << "插入位置输入有误" << endl;
return;
}
cout << "在" << i-1 << "位置插入s2(从0开始)" << endl;
s3.length = s1.length + s2.length;
for (int j = 0; j < i - 1; ++j)
s3.data[j] = s1.data[j];
for (int j = 0; j < s2.length; ++j)
s3.data[i-1+j] = s2.data[j];
for (int j = i - 1; j < s1.length; ++j)
s3.data[s2.length + j] = s1.data[j];
cout << "字符串插入成功" << endl;
for (int i = 0; i < s3.length; ++i)
cout << s3.data[i];
}
void RepStr(SqString& s1, SqString& s2, SqString& s3, int i, int j)
{
//replace the j characters starting from the ith character of the sequeence string s1 with the sequence string s2
//将顺序串s1的第i个字符开始的j个字符替换成顺序串s2
if (i<0 || j<0 || i>s1.length || i + j>s1.length)
{
cout << "输入参数有误" << endl;
return;
}
cout <<endl<< "第一轮复制s1的前 " << i - 2 << " 个字符(从0开始)" << endl;
for (int k = 0; k < i - 1; ++k)
{
s3.data[k] = s1.data[k];
cout << s3.data[k];
}
cout << endl << "第二轮复制s2的字符串" << endl;
for (int k = 0; k < s2.length; ++k)
{
s3.data[i - 1 + k] = s2.data[k];
cout << s3.data[i - 1 + k];
}
cout << endl << "第三轮复制s1符合要求的字符" << endl;
for (int k = i - 1 + j; k < s1.length; ++k)
{
s3.data[s2.length +k-j] = s1.data[k];
cout << s3.data[s2.length - 1 + i];
}
cout << endl;
cout << "替换成功" << endl;
cout << "新的字符串" << endl;
s3.length = s2.length + s1.length - j;
cout << "长度" << s3.length << endl;
for (int i = 0; i < s3.length; ++i)
cout << s3.data[i];
cout << endl;
}
int main()
{
char str1[] = "abcdrtfwwak";
char str2[] = "sryu";
SqString s1;
SqString s2;
StAssign(s1, str1);
StAssign(s2, str2);
SqString s3;
InsStr(s1, s2, s3, 5);
cout << endl << "字符串的替换" << endl;
SqString s4;
RepStr(s1, s2, s4, 3, 2);
}
|