Hi All,
So, I have a task to find number of substrings in given string. I can't use any C libraries for doing this task. stringExist can only have 2 strings as a parameters.
My solution is working, but I have a feeling that there should be a more elegant way to do this task. Solution 1: as it turns out, it doesn't work correctly
#include <stdio.h>
int stringExist(char string[], char s2[]);
int main(void){
char string[] = "strstrASDstrSTRst";
char s2[] = "str";
printf("Final result: %i\n",stringExist(string,s2));
return 0;
}
int stringExist(char string[], char s2[]){
/* I am aware that I can init all this values in one row */
int count = 0;
int size = 0;
int i = 0;
int temp = 0;
int result = 0;
while(s2[size]!='\0'){
size++;
}
while(string[i]!='\0')
{
if(string[i]==s2[0])
{
printf("Found first occurrence\n");
count=0;
while((temp=(string[i]==s2[count]))!=0)
{
count++;
if(size==count){
printf("Match\n");
result++;
break;
}
i++;
}
}
i++;
}
return result;
}
Solution number 2:
So far no errors found.
Did a little bit different string traversal, now I don't increment i in the compare chars loop.
#include <stdio.h>
int stringExist(char string[], char s2[]);
int main(void){
char string[] = "bobobobojkhhkjjkhbo;klkl;bobo";
char s2[] = "bobo";
printf("Final result: %i\n",stringExist(string,s2));
return 0;
}
int stringExist(char string[], char s2[]){
int count = 0;
int size = 0;
int i = 0;
int c = 0;
int temp = 0;
int result = 0;
while(s2[size]!='\0'){
size++;
}
for(i=0;string[i]!='\0';i++){
if(string[i]==s2[0])
{
printf("Found first occurence at %i\n",i);
count = 0;
c = i;
while((temp=(string[c]==s2[count]))!=0)
{
printf("Count %i, I %i, current char: %c\n",count, c,string[c]);
count++;
if(size==count){
printf("Match\n");
result++;
break;
}
c++;
}
}
}
return result;
}
Thanks for you suggestions, Vitaly