#include<string> #include<iostream> using namespace std; int main() { string s("12345asdf"); string a=s.substr(0,5);//获得字符串s中 从第0位开始的长度为5的字符串//默认时的长度为从开始位置到尾 cout<<a<<endl; }
1.strtok
ern char *strtok( char *s, const char *delim );
功能:分解字符串为一组标记串。s为要分解的字符串,delim为分隔符字符串。
说明:strtok()用来将字符串分割成一个个片段。当strtok()在参数s的字符串中发现到参数delim的分割字符时则会将该字符改为 \0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回被分割出片段的指针。当没有被分割的串时则返回NULL。所有delim中包含的字符都会被滤掉,并将被滤掉的地方设为一处分割的节点。
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
2.strchr
char * strchr ( const char *str, int ch );
功能:查找字符串 str 中首次出现字符 ch 的位置
说明:返回首次出现 ch 的位置的指针,如果 str 中不存在 ch 则返回NULL。/* strchr example */ #include <stdio.h> #include <string.h> int main () { char str[] = "This is a simple string"; char *pch; printf("Looking for the 's' character in \"%s\"...\n", str); pch = strchr(str, 's'); while (pch != NULL){ printf("found at %d th\n", pch - str + 1); pch = strchr(pch + 1, 's'); } return 0; }
3.substr
参考http://www.cplusplus.com/reference/