C/C++ std::string 字符串分割

ChatGPT 3.5 国内中文镜像站免费使用啦

零基础 C/C++ 学习路线推荐 : C/C++ 学习目录 >> C 语言基础入门

零基础 C/C++ 学习路线推荐 : C/C++ 学习目录 >> C++ 面向对象

零基础 C/C++ 学习路线推荐 : C/C++ 学习目录 >> C++ 设计模式

零基础 C/C++ 学习路线推荐 : C/C++ 学习目录 >> C++ STL

零基础 C/C++ 学习路线推荐 : C/C++ 学习目录 >> C/C++ 技术杂谈

零基础 C/C++ 学习路线推荐 : C/C++ 学习目录 >> C/C++ 常用函数


一.std::string 指定字符串分割

C++中使用 std::string 指定的单个字符或者字符串进行分割,并返回一个数组,示例代码如下:

/******************************************************************************************/
//@Author:猿说编程
//@Blog(个人博客地址): www.codersrc.com
//@File:C/C++ std::string 指定字符串分割
//@Time:2022/01/03 08:00
//@Motto:不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累!
/******************************************************************************************/

#include <iostream>
#include <string>
#include <vector>

std::vector<std::string> vStringSplit(const  std::string& s, const std::string& delim = ",")
{
	std::vector<std::string> elems;
	size_t pos = 0;
	size_t len = s.length();
	size_t delim_len = delim.length();
	if (delim_len == 0) return elems;
	while (pos < len)
	{
		int find_pos = s.find(delim, pos);
		if (find_pos < 0)
		{
			elems.push_back(s.substr(pos, len - pos));
			break;
		}
		elems.push_back(s.substr(pos, find_pos - pos));
		pos = find_pos + delim_len;
	}
	return elems;
}

int main()
{
	std::cout << "案例一:指定单个字符分割字符串" << std::endl;
	auto out1 = vStringSplit("www.codersrc.com",".");
	for (int i = 0; i < out1.size(); i++) {
		std::cout << out1[i] << std::endl;
	}

	std::cout << "案例二:指定字符串分割字符串" << std::endl;

	auto out2 = vStringSplit("www.codersrc.com", "code");
	for (int i = 0; i < out2.size(); i++) {
		std::cout << out2[i] << std::endl;
	}
	
	return 0;

}
/*
案例一:指定单个字符分割字符串
www
codersrc
com


案例二:指定字符串分割字符串
www.
rsrc.com

*/

二.猜你喜欢

  1. C语言 数组下标越界和内存溢出区别
  2. C语言 使用指针遍历数组
  3. C语言 指针和数组区别
  4. C语言 指针数组和数组指针区别
  5. C语言 野指针
  6. C语言 函数值传递和址传递
  7. 函数不定长参数
  8. C语言 函数指针
  9. C语言 指针函数
  10. C语言 回调函数 callback
  11. C语言 #pragma once
  12. C语言 #include <> 与 #include “” 区别
  13. C语言 const 修饰函数参数
  14. C语言 const 和 define 区别
  15. C语言 va_start / va_end / va_arg 自定义 printf 函数
  16. C语言 main 函数参数 main(int argc, char *argv[])
  17. C语言 结构体struct简介(一)
  18. C语言 结构体struct定义和使用(二)
  19. C语言 结构体struct数组(三)
  20. C语言 结构体struct指针(四)
  21. C语言 结构体struct成员函数(五)
  22. C语言 结构体struct嵌套(六)
  23. C语言 结构体struct值传递和址传递(七)
  24. C/C++ error: cannot assign to non-static data member within const member function ‘xxxx’
  25. C++ 关于类中 const 的使用
  26. C/C++ =delete
  27. C/C++ 条件编译 #ifdef
  28. C/C++ error C2065: “M_PI”: 未声明的标识符
  29. C/C++ error C2027: 使用了未定义类型“std::tuple”
  30. C/C++ vs 没有匹配 if 的非法 else 问题解决办法
  31. C/C++ Visual studio 中文注释导致编译不能通过
  32. C/C++ error C2589: “(”: “::”右边的非法标记
  33. C/C++ error:表达式是必须修改的左值
  34. C/C++ error C4996: ‘getch’: The POSIX name for this item is deprecated. Instead, use the ISO C++ conf
  35. C/C++ error C4146: 一元负运算符应用于无符号类型,结果仍为无符号类型
  36. C/C++ std::string 字符串分割

ChatGPT 3.5 国内中文镜像站免费使用啦
© 版权声明
THE END
喜欢就支持一下吧
点赞1 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容