字符串模式匹配和插入
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]!=' ')
{
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]=' ';
}
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)由于您想要在插入之后打印所有出现,因此需要删除上面的cout
,您可以在main()
或inspat()
的末尾(在for
循环之外)打印T
:
cout<<T<<endl;
3)由于插入发生在原始数组中,因此需要确保数组足够大。在main()
:
char T[256]="Good peo Good peo"; // 256 is some arbitrary size
相关文章:
- 模式匹配文本并提取C++中的数据
- 如何在CLIPS中优化不同模板事实之间的模式匹配
- Flex Lexer 模式匹配句子分隔符/标点符号作为 URL 路径部分
- C++中的模式匹配
- 模式匹配函数的时间测量无法正常工作
- QtLineEdit 占位符:如何让用户在插入模式下将字符 1 替换为 1
- C++向量的模式匹配
- 从.cpp文件中提取与模式匹配的"if"块
- 在某些情况下,通配符模式匹配失败
- 如何使用C++模板魔术来对类型进行模式匹配
- 使用 std::regex_search 获取与模式匹配的所有文件和文件夹
- 在 c++-17 中特化的模式匹配中 lambda 的拆分函数签名
- C++;仅当用户输入与预设模式匹配时才接受用户输入
- 下一个最大的整数,有一些中间位与模式匹配?
- 模板模式匹配
- 用于多个级联字符串的同步模式匹配算法
- 使用C++功能在系统路径中进行模式匹配
- 使用[msys]bash删除所有名称与模式匹配的文件,而不考虑文件名字母大小写
- DNA模式匹配中最快的算法是什么
- 字符串模式匹配和插入