views:

205

answers:

5

Given 2 strings, write a function that returns the position of String B that matches String A if String A is a substring of String B. Otherwise return -1. Example:

strA = "ello"
strB = "Hello_World"
Your function should return 1.

strA = "blah"
strB = "blha"
Your function should return -1.
+2  A: 

Is this homework? Anyway, look the string.h documentation and you should find what you need without much trouble. You will need to write a very thin wrapper over one of the functions. Or, of course, you can just write it all yourself.

EDIT: Well, someone else gave a answer, so here's my attempt.

#include <string.h>

ssize_t str_index(const char *strA, const char *strB)
{
    const char *result;
    return (result = strstr(strB, strA)) ? (result - strB) : -1;  
}

The only tricks are that the parameter order is reversed from strstr, you're returning an ssize_t instead of char *, and the failure code is thus -1.

Matthew Flaschen
Just wanted to say you are trusting strstr() to have a "nice" implementation, when it could be a morbid disaster.
Tom
And that size_t is unsigned. ssize_t should be used.
Tom
Good catch on ssize_t. Out of curiousity, does anyone know what (if any) warning level catches that with gcc? -Wall -Wextra does not.And yes, I'm deliberately trusting strstr because I have no reason not to.
Matthew Flaschen
+2  A: 

Brute force version:

int strpos(char* a, char* b) {
  int n1, n2, i, j;
  n1 = strlen(a);
  n2 = strlen(b);
  for (i = 0; i < n1-n2; i++) {
    for (j = 0; j < n2; j++) {
      if (a[i+j] != b[j]) break;
      else if (j+1 == n2) return i;
    }
  }
  return -1;
}

More effective algorithms: Wikipedia: String searching

MizardX
If you're going to use string.h anyway (or really even if you're not), why so verbose? Also, by doing strlen ahead of time, you lose most of your benefit from breaking out of the loop.
Matthew Flaschen
Just to show how it can be done.
MizardX
Yes, but as I said, that's a naive implementation, because of the strlen among other things.
Matthew Flaschen
A: 

This sounds almost exactly like a homework problem. In the strange case that it is not a homework problem, the C library function strstr returns a pointer to the first occurrence of a string inside another (or null if it is not there). From there, it is trivial to determine the index using pointer arithmetic.

Yuliy
+1  A: 
#include <string.h>

int search(char* a, char* b) {
    char* pos;
    pos = strstr(b, a);
    if(pos == 0) return -1;
    return (int)(pos-b);
}
Unknown
A: 

Trying learning about strstr. Its available in string.h There is NEVER a reason to code something already available in the standard library. Unless ofcourse, its a homework question :)

Aditya Sehgal
Its always not homework.At times people try to implement the function so they can get the working of the function in a better way
fahad
@fahad : fair enough but the way OP posed his question smelled like homework
Aditya Sehgal