我想比较两个字符串删除一个字符后是否完全匹配。
(索引从位置 0 开始)
例如
刺1:橙色
字符串2:年龄
输出应该是:
The string matches at position 2, after deleting position 3.
如何解决这个问题?
这是我现在的代码:
#include <stdio.h>
#include <string.h>
void search(char* pat, char* txt)
{
int M = strlen(pat);
int N = strlen(txt);
int j;
int position;
if (M > N)
{
printf("No Excat Matching");
}
for (int i = 0; i <= N - M; i++)
{
for (j = 0; j < M; j++)
{
if (txt[i + j] != pat[j]&&txt[i + j +1] != pat[j])
{
break;
}
}
if (j == M )
printf("The target string matches staring at position %d after deleting the
character at position %d\n",i,position);
}
}
int main()
{
char txt[100];
char pat[100];
printf("Enter some text\n");
gets(txt);
printf("Enter a string to find\n");
gets(pat);
search(pat, txt);
return 0;
}
最佳答案
首先尝试为字段和方法使用好的名称,以便将来其他人和您自己更容易阅读代码。
根据示例,您可以将两个参数命名为 comparisonString
和 searchedString
。
关于你的代码,你的长度比较很好。
对于第二部分,我将尝试仅使用一个for
。在其中迭代比较字符串。
在此,您应该首先尝试找到您的第一个字符。
一旦找到这个字符,您就需要检查其他字符是否也是您的字符串包含的字符。
如果不保存第一个不匹配的字符,一旦有两个不匹配的字符就停止迭代并返回该函数。如果需要,请先打印错误消息。
int numChar = 0;
int numUnmatchingChar = 0;
int firstMatchPos = -1;
int unmatchingCharPos = -1;
for(int i = 0; i < comparisonString; i++)
{
if(comparisonString[i] == searchedString[numChar])
{
if(numChar + 1 < M)
{
numChar++;
}
else
{
break;
}
if(firstMatchPos == -1)
{
firstMatchPos = i;
}
}
else if(firstMatchPos != -1)
{
if(unmatchingCharPos == -1)
{
unmatchingCharPos = i;
}
else
{
firstMatchPos = -1;
numChar = 0;
unmatchingCharPos = -1;
}
}
}
if(firstMatchPos != -1)
{
if(unmatchingCharPos != -1)
{
printf("The target string matches staring at position %d after deleting the
character at position %d\n",firstMatchPos,unmatchingCharPos);
}
else
{
printf("The target string matches staring at position %d);
}
}
这应该可以解决问题。但您只能找到一次。
关于c - 删除一个字符的字符串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53557201/