C 標準庫 – string.h之strstr使用

zhangrxiang發表於2019-05-11

strstr

  • Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.
  • 查詢 substr 所指的空終止位元組字串在 str 所指的空終止位元組字串中的首次出現。不比較空終止字元。
  • 若 str 或 substr 不是指向空終止位元組字串的指標,則行為未定義。
char *strstr(const char *haystack, const char *needle)

Parameters

haystack

  • C string to be scanned.
  • 要被檢索的 C 字串。

needle

  • C string containing the sequence of characters to match.
  • 在 haystack 字串內要搜尋的小字串。

Return Value

  • A pointer to the first occurrence in str1 of the entire sequence of characters specified in str2, or a null pointer if the sequence is not present in str1.
  • 該函式返回在 haystack 中第一次出現 needle 字串的位置,如果未找到則返回 null。

Example

//
// Created by zhangrongxiang on 2017/8/15 14:15.
// Copyright (c) 2017 ZRC . All rights reserved.
//

//#include <syslib.h>
#include <string.h>
#include <stdio.h>

//C 庫函式 char *strstr(const char *haystack, const char *needle) 在字串 haystack 中查詢第一次出現字串 needle 的位置,不包含終止符 ` `。

void find_str(char const *str, char const *substr) {
    char *pos = strstr(str, substr);
    if (pos) {
        printf("found the string `%s` in `%s` at position: %ld; result: %s
", substr, str, pos - str, pos);
    } else {
        printf("the string `%s` was not found in `%s`
", substr, str);
    }
}

int main() {
    char *s = "GoldenGlobalView";
    char *l = "lob";
    char *p;
    //返回值:若str2是str1的子串,則返回str2在str1的首次出現的地址;
    // 如果str2不是str1的子串,則返回NULL。
    p = strstr(s, l);
    if (p)
        //lobalView
        printf("%s
", p);
    else
        printf("NotFound!
");

    char *str = "one two three";
    find_str(str, "two"); //found the string `two` in `one two three` at position: 4; result: two three
    find_str(str, ""); // found the string `` in `one two three` at position: 0; result: one two three
    find_str(str, "nine");// the string `nine` was not found in `one two three`
    find_str(str, "n"); // found the string `n` in `one two three` at position: 1; result: ne two three

    char str2[] = "This is a simple string";
    char *pch;
    pch = strstr(str2, "simple");
    strncpy (pch, "sample", 6);
    puts(str2);//This is a sample string
    puts(pch);//sample string

    return 0;
}

文章參考

轉載註明出處

相關文章