跳轉到內容

C 程式設計/string.h/strstr

來自華夏公益教科書,開放的書籍,為開放的世界

strstr是 C 標準庫字串函式,定義在string.h. strstr()具有以下函式簽名char * strstr(const char *haystack, const char *needle);該函式返回指向第一個索引的字元的指標,其中needle位於haystack中,如果未找到則返回 NULL。[1]

該函式strcasestr()類似於strstr(),但它會忽略needlehaystack. strcasestr()的大小寫,這是一個非標準函式,而strstr()符合 C89 和 C99 標準。[1]

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

int main(void) 
{
	/* Define a pointer of type char, a string and the substring to be found*/
	char *cptr;
	char str[] = "Wikipedia, be bold";
	char substr[] = "edia, b";

	/* Find memory address where substr "edia, b" is found in str */
	cptr = strstr(str, substr);

	/* Print out the character at this memory address, i.e. 'e' */
	printf("%c\n", *cptr);

	/* Print out "edia, be bold" */
	printf("%s\n", cptr);
	
	return 0;
}

cptr現在指向 "wikipedia" 中的第六個字母 (e).

  • strchr

參考文獻

[編輯 | 編輯原始碼]
  1. a b strcasestr(3)
[編輯 | 編輯原始碼]
華夏公益教科書