C++中的一些技巧小结(一)

C++中的一些技巧小结(一)

1.如何通过vector的数组名来打印数组元素,需要用到<<重载

#include <iostream>
#include <vector>
#include <string>
using namespace std;
template <typename T>
ostream &operator <<(ostream &out, vector<T>&_vec)
{
	if (_vec.empty())
		return out;
	vector<T>::const_iterator it = _vec.begin();
	for (; it != _vec.end(); ++it)
	{
		out << *it<<" ";
	}
	return out;
}

int main()
{
	vector<int> vec(10, 1);
	cout << vec << endl;
	return 0;

}


2.string 向char char*、char []转化

2.1 char转string 这个最常用,string本身是一个数组,里面存放的是char类型

#include <iostream>
#include <string>
using namespace std;
inline string CharToString(char& temp)
{
    //char 转 string
	char t = temp;
	string s(1,t);
	return s;
}
int main()
{
	string s = "tgj hss";
	for (int i = 0; i < s.size(); i++)
	{
		string result = CharToString(s[i]);
		cout << result << endl;
	}
}

2.2 string转char 直接提取下表,即可


2.3 char*转string 可以直接赋值

string s;
char *p="tgj hss";
s=p;

2.4 string转char*,有三种方法:data(),c_str(),copy(),其中最常用的是c_str()

string str = "tgj hss";
const char* p = str.data();//加const  或者用char * p=(char*)str.data();的形式

string str = "tgj hss";
const char* p = str.c_str();//加const  或者用char * p=(char*)str.data();的形式

string str="hss";
char p[50];
str.copy(p, 5, 0);//这里5代表复制几个字符,0代表复制的位置,
*(p+5)=‘\0;//注意手动加结束符!!!

2.5 char []转string 可以直接赋值


2.6 string转char[]

string pp = "tgj hss";
char p[8];
int i;
for( i=0;i<pp.length();i++)
p[i] = pp[i];
p[i] = '\0';
printf("%s\n",p);
cout<<p;


3.字符串的切割函数

//src 为原字符串,condition为切割条件,返回值为按照条件切割好的字符串数组
std::vector<std::string> split(std::string src, std::string condition)
{
	std::vector<std::string> coll;
	int begin = 0, end = 0;
	while (begin < src.length())
	{
		end = src.find(condition.c_str(), begin);
		if (end == -1)
			end = src.length();
	     //第一个参数为起始位置,第二个参数为切几个
		coll.push_back(src.substr(begin, end - begin));
		begin = end + condition.length();
	}
	return coll;
}


4.循环查找字符串中符合条件的索引

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

vector <int> FindStringCondition(string src,string condition)
{
	vector<int> index_;
	int index_c=0;
	//string下的find函数,condition为查找的条件,index_c表示从哪开始
	while ((index_c = src.find(condition, index_c)) < src.length())
	{
		index_.push_back(index_c);
		index_c++;
	}
	return index_;
}

int main()
{
	string s = "tgj hss tgj hss tgj hss hss hss";
	vector<int> result = FindStringCondition(s, "hss");
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值