c++分割字符串:
http://www.martinbroadhurst.com/how-to-split-a-string-in-c.html
c分割字符串:
http://www.martinbroadhurst.com/split-a-string-in-c.html
下面是一种我使用的不需要外部库的方法:
使用strtok()函数分割字符串
C 库函数 char *strtok(char *str, const char *delim) 分解字符串 str 为一组字符串,delim 为分隔符。
char *strtok(char *str, const char *delim)
#include <string.h> #include <stdio.h> int main () { char str[80] = "This is - www.runoob.com - website"; const char s[2] = "-"; char *token; /* 获取第一个子字符串 */ token = strtok(str, s); /* 继续获取其他的子字符串 */ while( token != NULL ) { printf( "%s ", token ); token = strtok(NULL, s); } return(0); }
应用:从绝对路径中分割出文件名,需要使用split() 和 vector
char zss_file_fullpath[100]; strcpy(zss_file_fullpath, filepath.c_str()); const char *zss_sep = "/"; char *zss_temp_filename; std::vector<const char *> zss_reuslt; zss_temp_filename = strtok(zss_file_fullpath, zss_sep); while (zss_temp_filename != NULL) { zss_reuslt.push_back(zss_temp_filename); } outfile << zss_reuslt.back() << std::endl;
字符串复制:
突然发现对字符串函数缺乏系统的了解,所以花了一点时间专门整理下,在此记录之,以方便自己及有需要的人使用。
C/C++字符串函数的头文件:string.h
复制函数主要有4个,如下:
1、char * strcpy(char* destination,const char * source);
2、char* strncpy(char* destination,const char* source,size_t num);
3、void * memcpy(void* destination,const void* source,size_t num);
4、void * memmove(void* destination,const void* source,size_t num);
功能及用法说明:
1、strcpy:将由source指针指示的C 字符串(包括结尾字符)复制到destination指针指示的区域中。该函数不允许source和destination的区域有重叠,同时,为了避免溢出,destination区域应该至少和source区域一样大。
2、strncpy:复制source的前num字符到destination。如果遇到null字符(’