Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!thunder.mcrcim.mcgill.edu!snorkelwacker.mit.edu!spool.mu.edu!agate!linus!philabs!ttidca!hollombe From: hollombe@ttidca.TTI.COM (The Polymath) Newsgroups: alt.hackers Subject: Useful string function Message-ID: <27187@ttidca.TTI.COM> Date: 25 Jun 91 23:33:05 GMT Organization: The Cat Factory Lines: 62 Approved: yes Here's a simple minor hack I threw together. It's proved so useful, I'm amazed it isn't part of the standard Unix libraries. (C'mon. Even BASIC does this)! Anyway, it's a function that finds a substring within a string and returns its starting location or -1 if the substring isn't there. I'm sure you can think of many variations and improvements. This version does what I need it to. Enjoy. int Strloc (s1, s2) char *s1; /* String to be searched */ char *s2; /* String to search for */ { /*****************************************/ /* Locate substring s2 within string s1. */ /* Return starting position of s2. */ /* Return -1 if s2 not found in s1. */ /* */ /* Requires stdio.h. */ /* Calls strlen(). */ /* */ /* Placed in public domain 25 June 1991 */ /* by */ /* G. Hollombe (The Polymath) */ /*****************************************/ register int i, j; /* Loop indices */ register int s1_limit; /* Search limit in s1 */ register int s2_length; /* Length of s2 */ s2_length = strlen (s2); /* Minimize function calls. */ s1_limit = strlen (s1) - s2_length; /* If it ain't in here, it ain't. */ for (i = 0; i <= s1_limit; i++) /* Search s1 until not enough */ { /* characters left to hold s2. */ for (j = 0; j < s2_length; j++) { if (s1[i + j] != s2[j]) /* Mismatch? */ { if (j > 0) /* Yes, move i to start of mis- */ i += (j - 1); /* match (but don't back up) */ break; /* and start again. */ } /* end if */ } /* end for */ if (j >= s2_length) /* All matched? */ break; /* Yes, quit looking. */ } /* end for */ if (i > s1_limit) /* Found s2? */ return (-1); /* No, return -1 */ else return (i); /* Yes, return position */ } /* end Strloc() */ -- The Polymath (aka: Jerry Hollombe, M.A., CDP, aka: hollombe@ttidca.tti.com) Head Robot Wrangler at Citicorp Turn the rascals out! 3100 Ocean Park Blvd. (213) 450-9111, x2483 No incumbents in '92! Santa Monica, CA 90405 {rutgers|pyramid|philabs|psivax}!ttidca!hollombe