您的位置:首页 > 编程语言 > C语言/C++

C/C++中字符串截取的函数

2014-02-25 16:54 330 查看
用strtok函数,其函数声明为

char *strtok( char *strToken, const char *strDelimit );

在C++中应该有更好的方法,比如MFC中CString类中的成员函数SpanExcluding和[b]SpanIncluding都能达到截取字符串的作用。[/b]

[b]下面主要介绍strtok。strtok,[/b]SpanExcluding和SpanIncluding都可以在MSDN中找到详细的应用方法


参数

strTokenString containing token(s) 

strDelimit Set of delimiter characters 
返回值说明 All of these functions return a pointer to the next token found in strToken. They return NULL when no more tokens are found. Each call modifies strToken by substituting a NULL character for each delimiter that is encountered.
例子如下:

Example

/* STRTOK.C: In this program, a loop uses strtok
* to print all the tokens (separated by commas
* or blanks) in the string named "string".
*/

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

char string[] = "A string\tof ,,tokens\nand some  more tokens";
char seps[]   = " ,\t\n";
char *token;

void main( void )
{
printf( "%s\n\nTokens:\n", string );
/* Establish string and get the first token: */
token = strtok( string, seps );
while( token != NULL )
{
/* While there are tokens in "string" */
printf( " %s\n", token );
/* Get next token: */
token = strtok( NULL, seps );
}
}

Output

A string   of ,,tokens
and some  more tokens

Tokens:
A
string
of
tokens
and
some
more
tokens
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: