您的位置:首页 > 编程语言 > C语言/C++

C++中标准类string常用示例

2016-07-27 23:43 513 查看
好久没用过C++了,把常用的数据类型重新熟悉下。string平时用的较少,简单总结下。

#include <iostream>
#include <string>

using std::string;
using std::cout;
using std::endl;

int main()
{
// 初始化
string str1("Hello, World!");
cout << str1 << endl;

// 赋值操作
str1 = "This is a test";
cout << str1 << endl;

// 查询是否为空串
// 字符串中有多少个元素
if (!str1.empty())
{
cout << "There are " << (int)(str1.size()) << " elements." << endl;
}

// 取字符串中某个元素
cout << str1.at(3) << endl;
for (int i = 0; i < (int)(str1.size()); i++)
{
cout << str1[i] << endl;
}

// 清空字符串
str1.clear();
if (str1.empty())
{
cout << "This is a empty string" << endl;
}
return 0;
}


另外:
// string转换成为char数组
// c_str()函数可直接得到const char 字符串

 string str1 = "hello world";

 int len = (int)str1.size();

 char* str2 = (char*)malloc(len + 1);

 for (int i = 0; i < len + 1; i++)

 {

  str2[i] = str1[i];

  if (i == len)

   str2[i] = '\0';

 }

 printf("%s\n", str2);

 // char数组转换为string

 char str3[] = {"This is a test"};

 string str4;

 str4 = str3;

 cout << str4 << endl;

// string类的查找函数

find(),该函数有多种重载形式,可用来查找指定字符或者字符串在string中的位置。如:

size_t find(char c, size_t pos = 0) const 查找指定字符在string中位置,找到则返回其索引。如果没有找到,则返回string::npos。

// string类的输出字串的函数

substr(),该函数用来输出string的一个指定字串。如

basic_string substr(size_t index, size_t num = npos) 返回的子串从index开始,含num个字符。如果num默认为npos,则返回从index开始到字符串结束的所有字符组成的子字符串。

#include <iostream>
#include <string>

using namespace std;

int main()
{
char* test = "hello world";
string testStr = test;
string testStrSub;
cout << testStr << endl;
testStrSub = testStr.substr(3, 4);
cout << testStrSub << endl;

system("pause");
return 0;
}


成员函数string substr (size_t pos = 0, size_t len = npos) const;
值得注意的是函数的第二次参数为截取的长度,而非地址。如果没有指定长度len或len超出了源字符串的长度,则子字符串将延续到源字符串的结尾。
<
4000
br />

// string类的插入函数

insert(),可以用来在string中插入字符串或者字符。如

string &insert(size_t p, size_t n, char c) 表示在p处插入了n个字符c。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: