C++字符串

动态字符串

C++中定义一些来自c语言的字符串函数,在头文件中。通常,这些函数不直接操作内存分配。

  1. strlen(str)返回字符串长度,不包括\0

使用安全C库: strlen_s 也在

C++的string类

#include <string>

using namespace std;

const string s1("hello");
const string s2 = " world";
string s3 = s1 + s2;

在string类中,运算符 ==, +,>,<,[]等都被重载了

数值转换

string to_char(int);
string to_char(unsigned);
string to_char(long);
string to_char(unsigned long);
string to_char(long long);
...

demo

float f = 3.14;
string s3 =to_string(f);
cout << s3 << endl; /// 3.140000
int stoi(const string& str, size_t * idx = 0, int base = 10);

字符串转数值,idx: 未转换字符的索引,base:进制

demo

string s = "3.14";
float f = stof(s);
cout << f << endl;

原始字符串

  1. 单行
"hello \"world \""

等价于:

R"(hello "world ")"
  1. 跨行
R"(hello
world)"
  1. 特殊字符 ()

使用不会出现的字符作为分隔字符,如:

R"-hello (wolrd) !-"

在C++14中,只能使用()作为开始结束标识符,并且中间也可以输入括号字符

string s = R"(hello )wolrd) !)"; // C++14中合法

原文链接: https://www.cnblogs.com/zhuxiang1633/p/13235720.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++字符串

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/362243

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 下午2:16
下一篇 2023年3月2日 下午2:16

相关推荐