c++ - 字符串模式匹配和插入C++

标签 c++ algorithm matching

我正在尝试匹配并在字符串中插入一个模式。

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 字符数组:

strcpy(T, temp1);
cout<<T<<endl;

2) 因为你想在插入 all 之后打印,上面的 cout 需要去,你可以打印 T main() 或在 inspat() 处(在 for 循环之外):

cout<<T<<endl;

3) 由于插入发生在原始数组中,因此需要确保数组足够大。在 main() 中做一些类似的事情:

char T[256]="Good peo Good peo"; // 256 is some arbitrary size

关于c++ - 字符串模式匹配和插入C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31899627/

相关文章:

c++ - 制作具有平均值的随机数生成器

算法 - 创建考试时间表

r - 通过R中的模糊多对一字符串匹配匹配两个数据集

algorithm - 立体匹配-动态规划

c++ - 当多个进程使用该段时,Posix 共享内存使用 mremap 调整大小

c++ - 空 std::queue 将数据推送到陈旧项目的末尾

algorithm - 产业划分问题

javascript - 增加变量值直到它与 Javascript 中另一个变量的值相匹配的最快方法是什么?

嵌入许多简单变量和一个嵌套结构的结构的 C++ 深度复制..(memcpy?)

algorithm - 寻找通过特定顶点之间的最短路径