Find the occurrence of a substring in a string in C
Please tell me: there are two arrays of characters that are entered by the user, you need to check them character by character and find a substring in the string without using strstr, output the index of the first occurrence, I can not think of the right condition for the loop.
Here is the code of what is ready, you need to sort only in the cycles of the correct condition:
int main()
{
char str1[SIZE], str2[SIZE]; // объявляем массивы.
printf("Input string: ");
fill_str(str1); // вызываем функцию заполнения для первого массива(строка).
printf("Input pattern: ");
fill_str(str2); // вызываем функцию заполнения для второго массива(подстрока).
print_str(find_str(str1, str2)); // функция вывода с аргументом возвращаемого значения из функции сравнения строк.
getch();
return 0;
}
void fill_str(char str1[]) // заполнение массива.
{
gets(str1); // получаем ввод пользователя для заполнения массива
}
int find_str(char str1[], char str2[]) // функция для поиска строки в строкe.
{
int index;
//index = strstr(str1, str2); // ищем вхождение строки 2 в строку 1
for()
{
for()
{
}
}
return index; // возвращаем индекс
}
void print_str(int index) // функция вывода.
{
index == NULL ? printf("str1 not in str2") : printf("str1 in str2, entry index is: %d", index);
}
0
1 answers
for(i=0; str1[i]!='\0'; i++) {
for(j=i, k=0; str2[k]!='\0' && str1[j]==str2[k]; j++, k++)
;
if(k>0 && str2[k]=='\0')
{
index = i;
break;
}
}
2
Author: Daniel, 2019-08-28 08:46:18