C++3 - 分支语句if和string变量

一.if分支语句

C++的if分支语句和C语言没什么区别,可以参考我之前学的这篇文章:

C语言:分支循环-CSDN博客

二.string变量

string类型变量是字符串变量,和C语言不同,C++可以用string直接定义字符串变量,而C语言则需要用char类型实现。

要点:

1.需要引用头文件#include <string>

2.语法:string str

3.字符串字面量:const char* - 多个char组成,结尾是\0。

4.字符串变量本身存在栈区,但这个字符串本身存在堆区。

5.长度获取size(),不包含结尾处\0字符。

三.代码如下:

复制代码
#include <iostream>
#include<string> //string类型对应的头文件
using namespace std;
int main()
{
	std::string str1{ "test string 1" };//现代C++初始化直接加大括号就行。
	cout << "str1::" << str1 << endl;//初始化
	str1 = "test string 1-2";//赋值
	string str2{ str1 };//也是一个赋值方式
	cout << "str2::" << str1 << endl;
	string str3;//定义一个空串
	str3 = str2;
	cout << "str3:" << str3 << endl;

	//字符串的长度和空间
	string str4{ "123456789" };
	cout << "str4长度:" << str4.size() << endl;//求长度,不包括末尾\0
	cout << "str4空间:" << str4.capacity() << endl;//实际分配的空间大小

	//截断字符串
	cout << str4.substr(3) << endl;//从下标3开始
	cout << str4.substr(1, 3) << endl;//从下标1开始取三个数据

	string strif;
	//空串判断
	if (strif.empty())
	{
		cout << "strif empty" << endl;
	}
	if (strif.size() == 0)
	{
		cout << "strif empty" << endl;
	}
	if (strif == "")
	{
		cout << "strif empty" << endl;
	}
	string test1 = "abc";
	if (test1 != strif)
	{
		cout << "test1 not empty" << endl;
	}
	else
	{
		cout << "test1 empty" << endl;
	}

	//字符串和数字之间的转换
	auto i1 = stoi("1234");
	cout << "i1 = " << i1 << endl;
	string sd1 = "123.5";
	double d1 = stod(sd1);
	cout << "d1 = " << d1 << endl;
	auto f1 = stof("33.1f");
	cout << f1 << endl;
	auto f2 = stof("33.1");
	cout << f2 << endl;
	cout << stoll("-123123123123123") << endl;

	//数字转化为字符
	auto pistr = to_string(3.1415926);
	cout << "pistr = " << pistr << endl;
	cout << to_string(-19998) << endl;

	//6字符串拼接
	string log;
	string txt = "login success!";
	string user = "xcj";
	string suser = "cpp";
	int thread_id = 1023;
	log = user + ":" + txt + ":" + to_string(thread_id);
	log = "[debug]" + log;
	log += "。";
	cout << log << endl;

	//字符串的查找和替换
	string strfind = "test for find [user] test";//字符串的查找
	auto pos = strfind.find("[test]");
	string key = "[user]";//找到了返回[的下标位置

	pos = strfind.find(key);
	cout << "pos = " << pos << endl;

	if (pos == string::npos)
	{
		cout << "[test not found]" << endl;
		
	}
	auto bak = strfind;
	auto re = strfind.replace(
		pos, //被替换字符串的位置
		key.size(),//被替换字符串的长度
		suser);//要替换
	cout << bak << endl;
	cout << re << endl;
	
}
复制代码
相关推荐
apcipot_rain10 分钟前
C++开发 面试 1Day速通
开发语言·c++·面试
时间的情敌17 分钟前
Three.js GLTF 阀门 / 泵体模型加载、材质修改、状态联动(正常 / 故障 / 告警变色)
开发语言·javascript·three.js·材质
星恒随风39 分钟前
从0实现C++ AI大模型接入SDK(七):Ollama本地模型部署、NDJSON流式响应与LLMManager模型管理
linux·开发语言·c++·人工智能·笔记
琳少_2 小时前
java课堂笔记
java·开发语言·数据库·笔记
Brain 博览记3 小时前
脑机接口研究丨FPGA 5 毫秒完成运动想象分类
开发语言·论文阅读·人工智能·机器学习·fpga开发·分类·数据挖掘
Brain 博览记4 小时前
脑网络AI丨给图神经网络装上“信息高速路”
开发语言·网络·论文阅读·人工智能·深度学习·神经网络·机器学习
鱼很腾apoc5 小时前
【Redis】第2期 详解Redis五大数据结构:命令+C++实现、渐进式遍历与数据库管理
linux·服务器·c语言·数据结构·c++·redis·学习
郝学胜-神的一滴5 小时前
Effective Python 条款44:善用属性注解
开发语言·c++·vscode·python·算法·stl
bkspiderx16 小时前
C++符号冲突与内部符号优先策略详解
linux·服务器·c++·符号冲突·内部符号