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

好久没用过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超出了源字符串的长度,则子字符串将延续到源字符串的结尾。

// string类的插入函数

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

string &insert(size_t p, size_t n, char c) 表示在p处插入了n个字符c。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值