Home > Backend Development > C++ > body text

Usage of strstr function in c language

下次还敢
Release: 2024-04-29 19:51:16
Original
929 people have browsed it

The strstr() function searches a string for a substring, returning a pointer to the first matching substring or NULL (not found). The usage steps are as follows: 1. Search from the beginning of the string; 2. Compare character by character to find a match or reach the end of the string; 3. Return the matching character pointer if found, or NULL if not found.

Usage of strstr function in c language

Usage of strstr function in C language

The strstr function is used to find subcharacters in a string Standard C function for strings. It returns a pointer to the first matching substring, or NULL if no match is found.

Syntax:

<code class="c">char *strstr(const char *haystack, const char *needle);</code>
Copy after login

Parameters:

  • haystack: Characters to search for string.
  • needle: The substring to find.

Return value:

  • If needle is found in haystack, a pointer to the first character of needle is returned.
  • If needle is an empty string, return haystack.
  • If needle is not found in haystack, NULL is returned.

Usage:

The strstr function works as follows:

  1. It starts searching from the beginning of the haystack.
  2. It compares haystack and needle character by character until a match is found or the end of haystack is reached.
  3. If a match is found, it returns a pointer to the first matching character.
  4. If no match is found, it returns NULL.

Example:

<code class="c">#include <stdio.h>
#include <string.h>

int main() {
  char haystack[] = "Hello, world!";
  char needle[] = "world";

  char *result = strstr(haystack, needle);

  if (result) {
    printf("Found '%s' at position %ld\n", needle, result - haystack);
  } else {
    printf("'%s' not found in '%s'\n", needle, haystack);
  }

  return 0;
}</code>
Copy after login

Output:

<code>Found 'world' at position 7</code>
Copy after login

The above is the detailed content of Usage of strstr function in c language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!