C++字符串常见用法总结

1. 字符串与整数之间的转换

字符串转整数
  • 使用 std::stoi 将字符串转换为整数。
  • 使用 std::stol 将字符串转换为长整型。
  • 使用 std::stoul 将字符串转换为无符号长整型。
std::string strNum = "12345";
int num = std::stoi(strNum); // 转换为 int
long long numLong = std::stoll(strNum); // 转换为 long long
unsigned long long numUnsigned = std::stoull(strNum); // 转换为 unsigned long long
整数转字符串
  • 使用 std::to_string 将整数转换为字符串。
int num = 12345;
std::string strNum = std::to_string(num);

2. 字符串与浮点数之间的转换

字符串转浮点数
  • 使用 std::stof 将字符串转换为 float
  • 使用 std::stod 将字符串转换为 double
  • 使用 std::stold 将字符串转换为 long double
std::string strFloat = "123.45";
float floatVal = std::stof(strFloat);
double doubleVal = std::stod(strFloat);
long double longDoubleVal = std::stold(strFloat);
浮点数转字符串
  • 使用 std::to_string 将浮点数转换为字符串。
double num = 123.456;
std::string strNum = std::to_string(num);

3. 常见的字符串函数

检查字符串长度
  • 使用 length()size() 函数获取字符串长度。
std::string str = "Hello, World!";
size_t len = str.length();
字符串拼接
  • 使用 + 运算符或 append() 方法拼接字符串。
std::string str1 = "Hello, ";
std::string str2 = "World!";
std::string str3 = str1 + str2; // 使用 +
str1.append(str2); // 使用 append()
字符串查找
  • 使用 find() 函数查找子串位置。
std::string str = "Hello, World!";
size_t pos = str.find("World");
字符串替换
  • 使用 replace() 函数替换字符串的一部分。
std::string str = "Hello, World!";
str.replace(str.find("World"), 5, "Universe");
字符串删除
  • 使用 erase() 函数删除字符串的一部分。
std::string str = "Hello, World!";
str.erase(str.find("World"), 5);
字符串插入
  • 使用 insert() 函数在指定位置插入字符串。
std::string str = "Hello, ";
str.insert(7, "World!");
字符串比较
  • 使用 <, >, == 等运算符进行比较。
std::string str1 = "abc";
std::string str2 = "def";

if (str1 < str2) {
    std::cout << "str1 is less than str2" << std::endl;
} else if (str1 > str2) {
    std::cout << "str1 is greater than str2" << std::endl;
} else {
    std::cout << "str1 is equal to str2" << std::endl;
}
字符串分割
  • 使用 std::getline()std::istringstream 分割字符串。
std::string line = "one,two,three";
std::stringstream ss(line);
std::string item;
while (getline(ss, item, ',')) {
    std::cout << item << std::endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦星辰.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值