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/
c语言标准库里面没这个函数,如果你在代码中看到了这个函数,那一定是自定义的,没办法讲解用法。但是c++里面有这个方法(从根本上来说应该叫方法,不是函数),我给你讲讲c++里面这个函数的用法吧:
这个函数的原型是:basic_string substr( size_type index, size_type num = npos )
substr()返回本字符串的一个子串,从index开始,长num个字符。如果没有指定,将是默认值
string::npos。这样,substr()函数将简单的返回从index开始的剩余的字符串。
例如:
string s("What we have here is a failure to communicate")
string sub = s.substr(21)
cout <<"The original string is " <<s <<endl
cout <<"The substring is " <<sub <<endl
显示:
The original string is What we have here is a failure to communicate
The substring is a failure to communicate