一.if分支语句
C++的if分支语句和C语言没什么区别,可以参考我之前学的这篇文章:
二.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;
}