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;
	
}
复制代码
相关推荐
jimy11 小时前
c++类成员访问只看静态类型
开发语言·c++
承渊政道1 小时前
Linux网络学习【深入理解应用层HTTP协议、Cookie与Session机制及HTTPS协议原理】
linux·网络·学习·http·cookie·session
156082072191 小时前
银河麒麟 Qt 可执行文件打包说明
开发语言·驱动开发·qt
SEO_juper1 小时前
手写 llms.txt 验证器:让 AI 更愿意引用你的网站(GEO)
开发语言·人工智能·python·聚类·seo·独立站
CCCCCCCCharlie1 小时前
从0到1:一个字节的磁盘之旅
linux·开发语言·c++
比兔代理1 小时前
纯净IP是什么?从IP信誉、黑名单与ASN角度原理解析
开发语言·php
LuminousCPP1 小时前
数据库学习笔记(二):MySQL 基础操作入门|在 CentOS Stream 10 上连接、建库与建表
数据库·经验分享·笔记·学习·mysql·centos
benjiangliu1 小时前
恩培趣味计算机视觉-01-conda环境和Python库
开发语言·python·conda
艾莉丝努力练剑1 小时前
【AI大模型接入SDK】ChatServer接口实现
c++·人工智能·学习·ai·架构·大模型·sdk