N
N
nikitosssguy2014-05-14 15:38:46
C++ / C#
nikitosssguy, 2014-05-14 15:38:46

How to implement the search for one string in another in c++?

Since I am a beginner, I want to know how correct this solution is. Task: find the string for_search in the string string. What did I do wrong? How else can something like this be done? Thanks in advance for your replies.

int find_str(char *some, char *for_search){
  char *p, *j;
  for (int i = 0; some[i]; i++){
    p = &some[i];
    j = for_search;
    while (*p == *j && *p != 0){
      j++; p++;
    }
    if (!*j && (*p == ' ' ||  !*p)) return i;
    else {
      p = &some[i];
      j = for_search;
    }
  }
  return 0;
}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
1
1001001 111, 2014-05-14
@IgorO2

Take the source of some CRT.

char * __cdecl strstr (
            const char * str1,
            const char * str2
            )
    {
            char *cp = (char *) str1;
            char *s1, *s2;
     
            if ( !*str2 )
                return((char *)str1);
     
            while (*cp)
            {
                    s1 = cp;
                    s2 = (char *) str2;
     
                    while ( *s1 && *s2 && !(*s1-*s2) )
                            s1++, s2++;
     
                    if (!*s2)
                            return(cp);
     
                    cp++;
            }
     
            return(NULL);
     
    }

R
Rsa97, 2014-05-14
@Rsa97

Ugly:
You increment the value of a pointer and then get a character from it for something. Right:
In general, you have implemented the simplest algorithm. The list of algorithms can be viewed here .

E
egor_nullptr, 2014-05-14
@egor_nullptr

www.cplusplus.com/reference/cstring/strstr

X
xandox, 2014-05-14
@xandox

You have square time here + it’s not clear what exactly the function returns, well, more precisely, it returns 1 (true) if it found a string and 0 (false) if it didn’t find it, but often you need a place where the string begins.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question