• C++分割字符串方法


    C++标准目前没有提供分割字符串的方法,但可以自己实现之。

    测试代码如下:

    #include <vector>
    #include <string>
    #include <iostream>
    
    std::vector<std::string> Split(const std::string& str, const char* delim)
    {
    	std::vector<std::string> result;
    	size_t delim_len = strlen(delim);
    	std::string::size_type pos1 = 0;
    	std::string::size_type pos2 = str.find(delim);
    
    	while (pos2 != std::string::npos)
    	{
    		result.emplace_back(str, pos1, pos2 - pos1);
    
    		pos1 = pos2 + delim_len;
    		pos2 = str.find(delim, pos1);
    	}
    
    	if (pos1 != str.length())
    	{
    		result.emplace_back(str, pos1);
    	}
    
    	return result;
    }
    
    int main()
    {
    	std::string str = "hello|world|hi|cpp";
    
    	auto res = Split(str, "|");
    
    	for (const auto& item : res)
    	{
    		std::cout << item << std::endl;
    	}
    
    	std::cin.get();
    }
    
  • 相关阅读:
    方法
    Go中的OOP
    GO 结构体
    指针
    闭包
    回调函数
    匿名函数
    函数的数据类型及本质
    defer语句
    递归函数
  • 原文地址:https://www.cnblogs.com/demon90s/p/15612975.html
Copyright © 2020-2023  润新知