c/c++分割字符串

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字符(’’),且还没有到num个字符时,就用(num - n)(n是遇到null字符前已经有的非null字符个数)个null字符附加到destination。注意:并不是添加到destination的最后,而是紧跟着由source中复制而来的字符后面。下面举例说明:

char des[] = “Hello,i am!”;

char source[] = “abcdef”;

strncpy(des,source,5);

此时,des区域是这样的:a,b,c,,,i,空格,a,m,!

,并不是添加在!的后面。

这里,需要注意strcpy仅仅复制到null字符就结束了。

3、memcpy:将source区域的前num个字符复制到destination中。该函数不检查null字符(即将null字符当作普通字符处理),意味着将复制num个字符才结束。该函数不会额外地引入null字符,即如果num个字符中没有null字符,那么destination中相应字符序列中也没有null字符。同strcpy的区别:允许将source中null字符后面的字符也复制到destination中,而strcpy和strncpy则不可以。

4、memmove:同memcpy完成同样的功能,区别是,memmove允许destination和source的区域有重叠。而其他三个函数不允许。

例子:char str[] = “This is a test!”;

memmove(str+2,str+10,4);

此时,str变成:Thtests a test!

在C++中,对内存的掌握是尤其重要!

字符串拼接

std::string 类型的字符串,要拼接直接+就行了

#include <iostream>
#include <string>
using namespace std;

int main()
{
  const string str="hello ";
  const string str2="world";
  string n_str;
  n_str = str;
  n_str +=str2;
  cout<<n_str<<endl;
  return 0;
}
原文地址:https://www.cnblogs.com/zealousness/p/9971709.html