2013-10-12 2 views
1

Мне нужно написать код для задания, которое находит подстроку внутри строки.Поиск подстроки

Вот мой код, и я добавил комментарии:

// the target is the substring that we want to find in the source string 
// m is the length of the target, and n is the length of the source 
int contains(char target[], int m, char source[], int n) { 
int flag = 0; // the source originally does not contain the target 
int i; 

    // go through each character of the source string 
for(i = 0; i < n; i++) { 
    int targetIndex = 0; 
    int j; 

      // check if the preceding characters of the source string are a substring 
      // that matches the target string 
    for(j = i; j < n && targetIndex < m; j++) { 
     if(target[targetIndex] == source[j]) { 
      flag = 1; 
      targetIndex += 1; 
     } 
     else { 
      flag = 0; // a letter does not match 
      break; 
     } 
    } 
} 

return flag; 

}

Так что, когда я проверить этот метод, я всегда получаю 0 вернулся, и я не могу понять, почему.
Если я попробую int i = contains("potatoes", 8, "toes", 4);, он дает 0.
Я попытался поместить некоторые заявления печати, чтобы увидеть, какой символ он соответствует, и кажется, что он находит только первую букву "t".

+1

Поскольку это в основном просто 'strstr()', я предлагаю вам взглянуть на реализацию, e. г. один в glibc. –

+0

Изменить этот код? или хочет лучше? –

ответ

1

Перед началом матча вам необходимо нарушить внешний вид for.

Как работает ваш код, вы можете найти совпадение, затем снова запустить внешний цикл и «забыть» об этом.

1

Попробуйте так:

for(i = 0; i < n; i++) { 
    int targetIndex = 0; 
    int j; 

      // check if the preceding characters of the source string are a substring 
      // that matches the target string 
    for(j = i; j < n && targetIndex < m; j++) { 
     if(target[targetIndex] == source[j]) { 
      flag = 1; 
      targetIndex += 1; 
     } 
     else { 
      flag = 0; // a letter does not match 
      break; 
     } 
    } 
    if(flag == 1) 
    { 
    break; 
    } 
} 

Вы можете вместо этого попытаться с помощью функции strstr из С, который будет делать вещи проще для вас.

Пример:

char *x= "Find the substring in this string"; 
char *y= "substring"; 
if(strstr(x, y) != NULL) { 
    return true; 
} 
+0

вы наружный 'break;' безусловный –

+0

@GrijeshChauhan: - Спасибо Grijesh за указание на это. Обновлен мой ответ. Но я думаю, что второй вариант лучше, чем OP должен принять! –

+0

теперь это хорошо, но actaully вам не нужно 'else {..}' во внутреннем цикле, просто установите флаг = 0' перед циклом внешнего прерывания. Кроме того, не используйте 'break' вместо' return i; 'at внешний если. –

0

Немного модификация кода с пояснительными комментариями.

// the target is the substring that we want to find in the source string 
// m is the length of the target, and n is the length of the source 
int contains(char target[], int m, char source[], int n) { 
int flag = 0; // the source originally does not contain the target 
int i; 

    // go through each character of the source string 
for(i = 0; i < n; i++) { 
    int targetIndex = 0; 
    int j; 

      // check if the preceding characters of the source string are a substring 
      // that matches the target string 
    for(j = i; j < n && targetIndex < m; j++) { 
     if(target[targetIndex] == source[j]) { 
      targetIndex += 1; 
      if(targetIndex == m) { // the 'target' has been fully found 
       flag = 1; 
       break; 
      } 
     } 
     else 
     { 
      break; 
     } 
    } 
    if(flag == 1) // 'target' is already found, no need to search further 
    { 
     break; 
    } 
} 

return flag; 
} 

Разрыв внутреннего и внешнего контура, когда подстрока полностью найдена.

EDITED: Кроме того, вместо int i = contains("potatoes", 8, "toes", 4); оно должно быть int i = contains("toes", 4, "potatoes", 8); - согласно вашему описанию функции.

Смежные вопросы