c语言substr函数是什么意思

Python014

c语言substr函数是什么意思,第1张

c语言标准库函数中是没有substr函数的,除非你自定义实现。

c++语言标准库中的string类包含了一个substr函数。

在MSDN中,关于该函数的描述如下:

函数原型:

basic_string substr(size_type pos = 0,   size_type n = npos) const

功能描述:

The member function returns an object whose controlled sequence is a copy of

up to n elements of the controlled sequence beginning at position pos.

该函数返回一个包含了当前字符串从pos位置开始到第n个字符的子串对象副本。

函数参数:

pos 字符串截取的开始位置,从0开始计数。

n截取的字符长度,如果大于当前字符串可截取的有效字符长度,则默认截取有效长度

举例如下:

#include <stdlib.h>

#include <string>

using namespace std

int main() 

{

string sTest = "This is a test!"

string sSub = sTest.substr(0, 4)

printf("%s\n%d", sSub.c_str())

return 0

}

没有这个函数。

strstr()函数用来检索子串在字符串中首次出现的位置,其原型为:

char *strstr( char *str, char * substr )

【参数说明】str为要检索的字符串,substr为要检索的子串。

【返回值】返回字符串str中第一次出现子串substr的地址;如果没有检索到子串,则返回NULL。

头文件:#include <string.h>

【函数示例】strstr()函数的使用。

#include<stdio.h>

#include<string.h>

int main(){

char *str = "http://see.xidian.edu.cn/cpp/u/xitong/"

char *substr = "see"

char *s = strstr(str, substr)

printf("%s\n", s)

return 0

}

运行结果:

see.xidian.edu.cn/cpp/u/xitong/