How to write a C Program to Finds Sub-String Search in String in C Programming Language ?
This C Program to Finds sub-string search in string s.
Returns -1 if sub-string was not found
Returns 0 if search was empty
Returns starting index of sub-string if successful
Solution:
- int find(string s, string search)
- {
- if(length(search) == 0)
- {
- return 0;
- }
- int s_index = 0; //Starting index
- int c_index = 0; //Checking index
- int b_table[length(search)]; //Backtracking table
- fill_backtrack_table(*b_table, search);
- while(length(s) >= (s_index + c_index))
- {
- if(s.src[s_index + c_index] == search.src[c_index])
- {
- if(c_index == length(search) - 1)
- {
- return s_index;
- }
- else
- {
- c_index++;
- }
- }
- else
- {
- if(b_table[c_index] == -1)
- {
- s_index++;
- c_index = 0;
- }
- else
- {
- s_index += c_index - b_table[c_index];
- c_index = b_table[c_index];
- }
- }
- }*/
- return -1;
- }
- // Fills the backtrack table for function find
- void fill_backtrack_table(int* b_table, string search)
- {
- b_table[0] = -1;
- if(length(search) == 1)
- {
- return;
- }
- b_table[1] = 0;
- int t_index = 2; //Table index
- int s_index = 0; //Search index
- while (t_index < length(search))
- {
- if(search.src[t_index - 1] == search.src[s_index])
- {
- b_table[t_index] = s_index + 1;
- s_index++;
- t_index++;
- }
- else if(s_index > 0)
- {
- s_index = b_table[s_index];
- }
- else
- {
- b_table[t_index] = 0;
- t_index++;
- }
- }
- return;
- }