C++常用函数

一.字符串分割函数

  1. 使用strtok函数分割

原型:char *strtok(char *s, char *delim);
strtok在s中查找包含在delim中的字符并用NULL(’\0’)来替换,直到找遍整个字符串。
功能:分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。
说明:首次调用时,s指向要分解的字符串,之后再次调用要把s设成NULL。
strtok在s中查找包含在delim中的字符并用NULL(’\0’)来替换,直到找遍整个字符串。
返回值:从s开头开始的一个个被分割的串。当没有被分割的串时则返回NULL。
所有delim中包含的字符都会被滤掉,并将被滤掉的地方设为一处分割的节点。

char str[] = "now # is # good # country";
char delims[] = "#";
char *result = NULL;
result = strtok(str, delims);
while( result != NULL ) {
   cout<<result<<"\t";
   result = strtok( NULL, delims );
}
  1. 使用strstr函数分割

原型:extern char *strstr(char *str, char *needle);
功能:从字符串str中寻找needle第一次出现的位置(不比较结束符NULL)。
说明:返回指向第一次出现needle位置的指针,如果没找到则返回NULL。

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

int ParseWordsByLine(char* str_line)
{
	if(strlen(str_line) == 0)
	{
		return -1;
	}

	const char* needle=" ";
	char* buf = strstr(str_line, needle);
	while(buf != NULL)
	{
	    buf[0]='\0';
	    if(strlen(str_line) > 0)
	    {
	    	printf("%s\n", str_line);
	    }  
	    str_line = buf + strlen(needle);
	    buf = strstr(str_line, needle);
	}

	return 0;
}
int main() 
{
  char str[1024] = "  abd      re 43 s dc5 Ad ";
  ParseWordsByLine(str);
  return 0;
}

3.string类型分割

实例1:修改原有字符串

vector<string> split(string &str, const string &pattern)
{
    vector<string> result;
    str += pattern;
    int size = str.size();
    for(int i=0; i<size; ++i)
    {
        string::size_type pos = str.find(pattern,i);
        if(pos != string::npos)
        {
            string s = str.substr(i,pos-i);
            result.push_back(s);
            i = pos + pattern.size()-1;
        }           
    }
    return result;
}

实例2:不修改原字符串

void Split(const string &src, const string &separator, vector<string> &dest)
{
    string str = src;
    string substring;
    string::size_type start = 0;
    string::size_type index;
    do
    {
        index = str.find_first_of(separator, start);
        if (index != string::npos)
        {
            substring = str.substr(start, index - start);
            dest.push_back(substring);
            start = str.find_first_not_of(separator, index);
            if (start == string::npos) return;
        }
    }
    while (index != string::npos);

    //the last token
    substring = str.substr(start);
    dest.push_back(substring);
}

总结:strtok比较适合多个字符作分隔符(如按#;|分割)的场合,而strstr适合用字符串作分隔符的场合。

二.string去除首尾空白,trim

string trim(string &s)
{
    if (s.empty())return s;
    s.erase(0,s.find_first_not_of(" "));
    s.erase(s.find_last_not_of(" ") + 1);
    return s;
}

三.根据字符串调用同名函数(包含类函数)

#include<iostream>
#include <string>
#include <map>

using namespace std;

int add(int i,int j){ return i+j; }
int sub(int i,int j){ return i-j; }

typedef int (*FnPtr)(int,int);

class B;
typedef void (B::*FnPtrB)();

class B{
public:
	map<string, FnPtrB> fun_map;

	B::B();
	void execute(const string &fun);
	void set();
};

B::B()
{
	fun_map["set"] = &B::set;
}

void B::set()
{
	printf("B-set");
}

void B::execute(const string &fun)
{
	(this->*fun_map[fun])();
}

int main()
{
     map<string,FnPtr> myMap;

     myMap["add"] = add;
     myMap["sub"] = sub;

     std::string s("add");
     int res=myMap[s](1,2);

     cout<<res<<endl;

	 B* b = new B;
	 b->execute("set");

     return 0;
}

四. Linux遍历文件夹下文件

用stat函数判断文件类型。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h> 
#include <dirent.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sstream>
using namespace std;

int main(int argc, char const *argv[]) 
{ 
    if(argc != 2)
    {
        printf("input dirent\n");
        return -1;
    }
    struct dirent *pDirEntry = NULL;
    DIR *pDir = NULL;
    if((pDir = opendir(argv[1])) == NULL)
    {
       printf("cannot open dirent %s\n", argv[1]);
       return -1;
    }
    while(pDirEntry = readdir(pDir))
    {   
        if (strcmp(pDirEntry->d_name, ".") == 0 || strcmp(pDirEntry->d_name, "..") == 0)
        {
            continue;
        }

        string file_name = pDirEntry->d_name;
        string::size_type pos = file_name.find('.');
        if(pos != string::npos)
        {   
            //文件后缀名
            string extension = file_name.substr(pos + 1);
            printf("%s extension is %s\n", pDirEntry->d_name, extension.c_str());
        }

        stringstream ss;
        ss<<argv[1]<<pDirEntry->d_name;

        struct stat buf; 
        stat(ss.str().c_str(), &buf); 
        if(S_IFDIR & buf.st_mode){
            printf("%s is folder\n", pDirEntry->d_name);
        }else if(S_IFREG & buf.st_mode){ 
            printf("%s is file\n", pDirEntry->d_name);
        }
    }

    return 0; 
}

五.用sfinae特性判断一个类型是否有某个函数

#include <iostream>
#include <vector>
#include <map>

//判断类型C是否有size()函数
template <typename T>
class HasSize {
private:
  typedef char Yes;
  typedef Yes No[2];
 
  template <typename U, U> struct really_has;
 
  template<typename C> static Yes& Test(really_has <size_t (C::*)() const, &C::size>*);
  template<typename C> static Yes& Test(really_has <size_t (C::*)(), &C::size>*);
 
  template<typename> static No& Test(...);
 
public:
    static bool const value = sizeof(Test<T>(0)) == sizeof(Yes);
};

int main(int argc, char const *argv[])
{
	std::cout << "vector.size():" << HasSize<std::vector<std::string> >::value << std::endl;
	std::cout << "int.size():" << HasSize<int>::value << std::endl;
	std::cout << "map.size():" << HasSize<std::map<std::string, int> >::value << std::endl;
	return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值