Home  >  Article  >  Backend Development  >  Usage of strstr function in c++

Usage of strstr function in c++

下次还敢
下次还敢Original
2024-05-09 03:51:21350browse

The strstr() function in C searches for a substring in the specified string and returns the position of the first character in the substring or NULL. The function uses the KMP algorithm to preprocess substrings first to improve search efficiency.

Usage of strstr function in c++

Strstr() function usage in C

Definition and syntax

strstr() function is used to find the first occurrence of another substring in a string. The syntax is as follows:

<code class="cpp">char *strstr(const char *str, const char *substr);</code>

Where:

  • str: The string to be searched.
  • substr: The substring to be found.

Return value

If the substring is found, the strstr() function returns a string pointer containing the first character of the substring, otherwise it returns NULL.

Usage Instructions

The strstr() function uses the KMP algorithm (Knuth-Morris-Pratt algorithm) for string matching. It preprocesses substrings first and then scans the string, thus improving search efficiency.

Example Usage

The following code example demonstrates how to use the strstr() function:

<code class="cpp">#include <iostream>
#include <cstring>

using namespace std;

int main() {
  char str[] = "Hello, world!";
  char substr[] = "world";

  char *result = strstr(str, substr);

  if (result) {
    cout << "Substring '" << substr << "' found at position " << (result - str) << endl;
  } else {
    cout << "Substring not found" << endl;
  }

  return 0;
}</code>

Output:

<code>Substring 'world' found at position 7</code>

Note

  • #strstr() function is case-sensitive.
  • If the substring is empty, the strstr() function will return a pointer to the original string.
  • If the substring is longer than the string, the strstr() function will return NULL.

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

Statement:
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