续:string的用法

续:string的用法

  • 1、字符串插入
  • 2、c_str
  • 3、分隔后缀
  • 4、字符串转化为数值,或数值转化为字符串

1、字符串插入

#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 
using namespace std;

void test_string8()
{
	//insert 尽量少用
	string str("wo lai le");
	//(1)在空格的位置插入 20%
	for (size_t i = 0; i < str.size(); ++i)
	{
		if (' ' == str[i])
		{
			str.insert(i, "20%");
			i += 4;
		}
		else
		{
			++i;
		}
	}
	cout << str << endl;

	//(2)用 20% 替换空格

	// 先插入20%,再删除空格
	for (size_t i = 0; i < str.size(); ++i)
	{
		if (' ' == str[i])
		{
			str.insert(i, "20%");
			i += 3;
		}
	}
	cout << str << endl;

	for (size_t i = 0; i < str.size(); ++i)
	{
		if (' ' == str[i])
		{
			str.erase(i, 1);
		}
	}
	cout << str << endl;


	//用空间换时间
	string newstr;
	for (size_t i = 0; i < str.size(); ++i)
	{
		if (str[i] != ' ')
		{
			newstr += str[i];
		}
		else
		{
			newstr += "20%";
		}
	}
	cout << newstr << endl;

}

2、c_str

void test_string9()
{
	//要求:用C的形式读文件  // c_str() 是为了兼容一些c语言的用法而使用的。
	string filename("test.cpp");
	cout << filename << endl;
	cout << filename.c_str() << endl;

	filename += '\0';
	filename += "string.cpp";
	cout << filename << endl; //string对象 终止的标准是 _size;
	cout << filename.c_str() << endl; //而常量字符串的 终止标准是 '\0'


	cout << filename.size() << endl;
	string copy = filename;
	cout << copy << endl;

	/*FILE* fout = fopen(filename.c_str(),"r");
	assert(fout);

	char ch = fgetc(fout);
	while (ch != EOF)
	{
		cout << ch;
		ch = fgetc(fout);
	}*/
}

3、分隔后缀

void DealUrl(const string& url)
{
	size_t pos1 = url.find("://");
	if (pos1 == string::npos)
	{
		cout << "非法url" << endl;
		return;
	}

	string protocol = url.substr(0, pos1);
	cout << protocol << endl; //打印 协议

	size_t pos2 = url.find('/', pos1 + 3);
	if (pos2 == string::npos)
	{
		cout << "非法url" << endl;
		return;
	}

	string domain = url.substr(pos1 + 3, pos2 - pos1 - 3);
	cout << domain << endl; //打印 域名

	string uri = url.substr(pos2 + 1);
	cout << uri << endl; //打印 统一资源标识符

}

void test_string10()
{
	//string filename("test.cpp.tar.zip");
	后缀
	//size_t pos = filename.rfind('.');
	//if (pos != string::npos)
	//{
	//	//string suff = filename.substr(pos,filename.size()-pos);
	//	string suff = filename.substr(pos);
	//	cout << suff << endl;

	//}

	string url1 = "https://cplusplus.com/reference/string/string/";
	string url2 = "ftp://ftp.cs.umd.edu/pub/skipLists/skiplists.pdf";

	DealUrl(url1);
	cout << endl;
	DealUrl(url2);

}

4、字符串转化为数值,或数值转化为字符串

void test_string12()
{
	int ival;
	double dval;
	cin >> ival >> dval;
	string istr = to_string(ival); //整型转化为字符串
	string dstr = to_string(dval);
	cout << istr << endl;
	cout << dstr << endl;

	istr = "9999";
	dstr = "9999.99";
	ival = stoi(istr); // 字符串转化为整型
	dval = stod(dstr);
	cout << ival << endl;
	cout << dval << endl;
}

int main()
{
	test_string12();

	return 0;
}

你可能感兴趣的:(c++)