子字符串是提取给定字符串的某些部分的操作。大多数流行的和最新的编程语言都提供了一个用于子串操作的函数。C语言提供了不同的方法和函数来实现子串操作。
null
什么是子串操作?
子字符串用于根据指定的参数返回给定字符串的某些部分。例如,我们可以在字符串“WiseTut.com”中搜索“Tut”项,如果我们使用子字符串,它将返回“Tut”。或者,我们可以指定start和length参数以返回子字符串。索引从0开始,我们将指定4作为起始索引。长度为3,因为“Tut”中有3个字符。
实际上有两种方法返回子字符串。第一个是 strstr() 用于在给定字符串中查找字符串的函数。就像大海捞针一样。第二种方法是用C语言创建我们自己的子串。
带strstr()函数的子字符串
strstr() 函数提供了 字符串.h 图书馆。它只接受两个参数,其中第一个参数是要在其中搜索的字符串,第二个参数是要在第一个字符串中搜索的术语。strstr()函数的语法如下所示。
char *strstr(const char *haystack, const char *needle);char *strstr(const char *haystack, const char *needle);char *strstr(const char *haystack, const char *needle);
- 常量字符*干草堆 是我们要搜索的完整字符串。类型是char pointer,它是C中的一个等价字符串。
- 常量字符*指针 将在大海捞针中搜索的搜索项。指针是字符串的char指针。
- 字符*字符串(…) 函数名和返回类型,返回指针的第一个出现指针。
我们将为C strstr()函数创建一个示例,以获得子字符串的开始。我们将提供
#include <stdio.h>#include <string.h>int main () { const char haystack[20] = "WiseTut.com"; const char needle[10] = "Tut"; char *ret;ret = strstr(haystack, needle);printf("The substring start is: %s", ret);return(0);}#include <stdio.h>#include <string.h> int main () { const char haystack[20] = "WiseTut.com"; const char needle[10] = "Tut"; char *ret; ret = strstr(haystack, needle); printf("The substring start is: %s", ret); return(0);}#include <stdio.h>#include <string.h> int main () { const char haystack[20] = "WiseTut.com"; const char needle[10] = "Tut"; char *ret; ret = strstr(haystack, needle); printf("The substring start is: %s", ret); return(0);}
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END