[英]String pattern matching and insertion C++
我正在嘗試匹配並在字符串中插入模式。
在這里,在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);
}
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.