C++中的string用法

大家好,我是发哥,今天我们来说说C++中string类常用方法。

直接通过实例说明,大家遇到直接使用就好了。

示列代码如下:

#include <iostream>

#include <string>

using namespace std;

int main()

{

{


string val_str = "Hello World";

cout << "[cout] val_str is: " << val_str << endl;

// string 转换为 char*

const char* pchar_buf = val_str.c_str();

printf("[printf] pchar_buf is: %s\n", pchar_buf);


}


{

//比较两字符串是否相等

string str_one = "Hello World";

string str_two = "Hello World";

int nLen = str_one.length();


cout << "the length of str_one is: " << nLen << endl;

if (0 == str_one.compare(str_two))

{

cout << "str_one equal with str_two" << endl;


}

else

{

cout << "str_one not equal with str_two" << endl;

}


}


{

//判断是否是空字符串

string str;

if (str.empty())

{

cout << "str is empty." << endl;

}

else

{

cout << "str is not empty." << endl;

}


}



{

//char* 转换为 string

char *pchar_name = "lilei";

string strName;


strName = pchar_name;


cout << "strName is: " << strName << endl;


}


{

//字符串插入

string str = "I am";


str.insert(4, " fine.");


cout << "str is: " << str << endl;


}

return 0;

}

示列运行结果如下截图:


今天就说到这,谢谢你的关注,记得点赞、评论和关注哦,后期会有更好的优秀作品呈现,你的支持是我创建继续创造优秀作品的动力。

明天早上六点我们继续再聊!

原文链接:,转发请注明来源!