现在的位置: 首页 > 综合 > 正文

C/C++中的Split函数

2013年01月26日 ⁄ 综合 ⁄ 共 917字 ⁄ 字号 评论关闭

 C/C++中的Split函数是strtok()其函数原型如下:
char * strtok (char * str, const char * delimiters);

函数说明
 strtok()用来将字符串分割成一个个片段。参数str指向欲分割的字符串,参数delimiters则为分割字符串,当strtok()在参数str的字符串中发现到参数delimiters的分割字符时则会将该字符改为'/0'字符。在第一次调用时,strtok()必需给予参数str字符串,往后的调用则将参数str设置成NULL。每次调用成功则返回下一个分割后的字符串指针。

返回值
 返回下一个分割后的字符串指针,如果已无从分割则返回NULL。

示例-1
/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="a,b,c,d*e";
  const char * split = ",";
  char * p; 
  p = strtok (str,split); 
  while(p!=NULL) {
    printf ("%s/n",p);
    p = strtok(NULL,split);
  }
  
  getchar();
  return 0;
 
}
本例中,实现对字符串'a,b,c,d*e"用逗号(,)来作界定符对字符串进行分割。
输出结果将如下所示:
a
b
c
d*e

因为delimiters支持多个分割符, 我们将本示例中的语句行
  const char * split = ",";
改成   const char * split = ",*"; //用逗号(,)和星号(*)对字符串进行分割

这样输出结果将如下所示:
a
b
c
d
e

更多strtok函数的功能,请参考相关 C++ Library Reference。

Standard C++ Library Reference (Standard C++ Library)
A C++ program can call on a large number of functions from this conforming implementation of the Standard C++ Library. These functions perform essential ...

抱歉!评论已关闭.