編輯 我重排的代碼和固定循環bugs.Now陣列,做工精細,但仍然有一個問題there.Loop迭代,並查找字符串中的模式,然後標記it.After,它不斷迭代,發現另一相同然後標記它,但是在做這件事時,它會重置第一個標記的圖案。這樣控制檯輸出就像爲什麼數組在C中的字符串後有路徑?
輸出
found at 3 to 6
hi
<mark>how</mark> are you
fine
how are you to
found at 20 to 23
hi
how are you
fine
<mark>how</mark> are you to
/我如何可以存儲第一陣列?我無法處理爲const char數組風格/
/*我想輸出像即:
found at 3 to 6
hi
<mark>how</mark> are you
fine
how are you to
found at 20 to 23
hi
<mark>how</mark> are you
fine
<mark>how</mark> are you to
我,如果你幫助非常心存感激
我想用蠻力算法做字符串匹配。我認爲,我正確地編寫了算法,並且運行良好。但我有一個問題。即使模式在字符串中多次,該算法也只能找到一個模式。它只找到第一個。所以我嘗試在for循環中反覆調用它。但我有一個問題。當我嘗試一遍又一遍地打電話時,它弄亂了我的數組。在運行時我看到一些路徑,即使沒有在我的數組中?這可能是什麼原因?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 200
char *textCOOL;
/* try to find the given pattern in the search string */
int bruteForce(char *text, char *pattern,int stringlength,int patternlength) {
char *text2;
text2 = (char *) malloc(MAX);
textCOOL = (char *) malloc(MAX);
int i, j;
int p=1;
for (i = 0; i <= stringlength - patternlength; i++) {
j=0;
while (j < patternlength && pattern[j]==text[i+j]){
j=j+1;
if(j==patternlength){
int lentino;
lentino=patternlength+(i);
printf("from %d to %d i found\n",i,lentino);
p=0;
int start1;
int start2;
int start3;
for(start1=0;start1<i;start1++){
text2[start1]=text[start1];
}
text2[i]='<';
text2[i+1]='m';
text2[i+2]='a';
text2[i+3]='r';
text2[i+4]='k';
text2[i+5]='>';
for(start2=0;start2<patternlength;start2++){
text2[(i+6+start2)]=pattern[start2];
}
text2[(i+6+patternlength)]='<';
text2[(i+7+patternlength)]='/';
text2[(i+8+patternlength)]='m';
text2[(i+9+patternlength)]='a';
text2[(i+10+patternlength)]='r';
text2[(i+11+patternlength)]='k';
text2[(i+12+patternlength)]='>';
for(start3=0;start3<stringlength-1;start3++){
if(text[i+patternlength+start3]=='\0'){
text2[((i+13+patternlength)+start3)]='\0';
break;
}
else{
text2[((i+13+patternlength)+start3)]=text[i+patternlength+start3];
}
}
printf("%s",text2);
}
}
}
if(p==1){
printf(" Not found\n");
}
}
int main() {
char searchStr[MAX], pattern[MAX];
int res;
char j;
FILE *fp;
int start;
int end;
start=0;
end=MAX;
fp = fopen("deneme.txt", "r");
if (fp == NULL) {
printf("I couldn't open deneme.txt for writing.\n");
exit(0);
}
int i;
for(i=0; i<MAX; i++){
j='\0';
fscanf(fp,"%c",&j);
searchStr[i]=j;
}
printf("%s\n",searchStr);
fclose(fp);
printf("Enter Pattern String:");
fgets(pattern, MAX, stdin);
searchStr[strlen(searchStr)-1] = '\0';
pattern[strlen(pattern)-1] = '\0';
res = bruteForce(searchStr, pattern, strlen(searchStr), strlen(pattern));
return 0;
}
爲了回答這個問題,必須提供文件「deneme.txt」的內容。編輯您的問題並顯示'deneme.txt'的內容。 –