1. 程式人生 > 實用技巧 >C++字串

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中合法