1

strstr() is great but it does not allow search in the first n characters of the first argument. Suppose only first n character of char a[100] are relevant. Is there a function in C which searches only in first n characters of a?

Catiger3331
  • 611
  • 1
  • 6
  • 18
  • 1
    `strnstr` takes length parameter. – hyde Sep 16 '19 at 05:00
  • You can write your own wrapper around `strstr()` to suit above need. – जलजनक Sep 16 '19 at 05:03
  • 1. Create your own custom strstr function which will run till the required length. 2. If you know the size, you can create a new char array using malloc and use it for strstr function. – Mohit Jain Sep 16 '19 at 05:06
  • 1
    Swap out the nth char with NUL, use strstr(), swap in again. So many ways....... – Martin James Sep 16 '19 at 05:27
  • If you know that both arrays are greater than n bytes, and you're OK with GNU extensions, and your strings UTF8-compatible, you can try `memmem()`. – root Sep 16 '19 at 06:29
  • @MartinJames That would be quite bad, because then you couldn't pass a `const char*` parameter, because you are going to modify the string. Even worse, string literal are of non-const pointer type, yet writing to string literal causes segmentation fault in many current operating systems and is Undefined Behavior in the standard. So it would be very easy to accidentally use the function on string literal and make a program that crashes. Since it is Undefined Behavior, also something else, much worse than a crash, could happen. – hyde Sep 16 '19 at 08:49
  • @SparKot Writing a wrapper around `strstr`, how exactly? How would you get `strstr` to stop searching after some specific number of chars in the wrapper function? (Other than modifying the string, which as explained in my above comment would be bad.) – hyde Sep 16 '19 at 08:51
  • @hyde very true. I surely would not do that in a library function:) – Martin James Sep 16 '19 at 11:21

1 Answers1

2

Duplicate of Implementing strnstr

On some platforms strnstr is present, on some not, so it's not portable.

You may use FreeBSD version shown below.

Note that older versions of this function contained bug that caused read access violation in some circumstances! More info here.

Libc-391.5.22 and earlier contain the bug.

Libc-498 and later have it fixed.

/*-
 * Copyright (c) 2001 Mike Barcroft <mike@FreeBSD.org>
 * Copyright (c) 1990, 1993
 *  The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Chris Torek.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <string.h>

/*
 * Find the first occurrence of find in s, where the search is limited to the
 * first slen characters of s.
 */
char *
strnstr(const char *s, const char *find, size_t slen)
{
    char c, sc;
    size_t len;

    if ((c = *find++) != '\0') {
        len = strlen(find);
        do {
            do {
                if (slen-- < 1 || (sc = *s++) == '\0')
                    return (NULL);
            } while (sc != c);
            if (len > slen)
                return (NULL);
        } while (strncmp(s, find, len) != 0);
        s--;
    }
    return ((char *)s);
}
4LegsDrivenCat
  • 1,247
  • 1
  • 15
  • 24
  • I've just referenced newer version of FreeBSD strnstr function in my answer because previous one contained the bug! Update your code if you used old one. – 4LegsDrivenCat Mar 05 '20 at 21:38