我正在尝试匹配并在字符串中插入一个patern。
此处Good peo Good peo
,我正在搜索peo
并插入ple
。
但输出就是这样:
Good people Good peo /n
Good peo Good people
我需要输出像
Good people Good people
我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
int length(char s[])
{
int len=0;
int i=0;
while(s[i]!='\0')
{
i++;
len++;
}
return len;
}
void concatenate(char s1[], char s2[])
{
int i=length(s1);
int j=length(s2);
int count=0;
while(count<=j)
{
s1[i]=s2[count];
i++;
count++;
}
}
void substring(char s[], char dest[], int ip, int len)
{
int i=ip;
int count=0;
while(count<len)
{
dest[count]=s[i];
count++;
i++;
}
dest[count]='\0';
}
void ins(char T[], int ip, char P[])
{
char temp1[100];
char temp2[100];
substring(T, temp1, 0, ip);
substring(T, temp2, ip, length(T)-ip);
concatenate(temp1, P);
concatenate(temp1, temp2);
T=temp1;
cout<<T<<endl;
}
void del(char T[], int ip, int L)
{
char temp1[100];
char temp2[100];
substring(T, temp1, 0, ip);
substring(T, temp2, ip+L, length(T)-ip-L);
concatenate(temp1, temp2);
T=temp1;
cout<<T<<endl;
}
//where T is the original string and P is the pattern to be deleted whereever it appears in the original string.
void delpat(char T[], char P[])
{
char temp[100];
for(int i=0; i<=length(T); i++)
{
substring(T, temp, i, length(P));
if(strcmp(temp, P)==0)
del(T, i, length(P));
}
}
//where T is the original string, Q is the pattern to be inserted and P is the pattern after which it is inserted.
void inspat(char T[], char P[], char S[])
{
char temp[100];
for(int i=0; i<=length(T); i++)
{
substring(T, temp, i, length(P));
if(strcmp(temp, P)==0)
ins(T, i+length(P), S);
}
}
int main()
{ char a[100];
char T[]="Good peo Good peo";
char P[]="peo";
char S[]="ple";
inspat(T, P, S);
gets(a);
}
答案 0 :(得分:2)
1)函数ins()
中的赋值不会更改调用者的值:
T=temp1;
cout<<T<<endl;
您需要使用strcpy()
复制temp1
char数组:
strcpy(T, temp1);
cout<<T<<endl;
2)由于您要打印插入所有次后的内容,因此需要执行上述cout
,您可以在T
中打印main()
或在inspat()
(for
循环之外):
cout<<T<<endl;
3)由于插入发生在原始数组中,因此需要确保数组足够大。做main()
:
char T[256]="Good peo Good peo"; // 256 is some arbitrary size