std::string

一、另类的构造方式

1. string s(cp, n)

s是cp指向的数组中前n个字符的拷贝。//此数组应该至少包含n个字符

        char cp[] = "i am a cp array";
        std::string s(cp, 9);
        std::cout << s << std::endl;

输出:

i am a cp

2.string s(s2, pos2)

s是string s2从下标pos2开始的字符的拷贝。

		std::string s2 = "i am s2";
        std::string s(s2, 2);
        std::cout << s << std::endl;

输出:

am s2

3.string s(s2, pos2, len2)

s是string s2从下标pos2开始len2个字符的拷贝。最多拷贝到s2的最后。

		std::string s2 = "i am s2";
        std::string s(s2, 2, 4);
        std::cout << s << std::endl;

输出:

am s

二、find和substr

1、find使用

size_type find(const basic_string& __str, size_type __pos = 0)

返回值为字符串中初次找到子字符串str时的下标。pos为起始查找的位置。如果搜索失败,则返回std::string::npos。

		std::string s = "i will test find test";
        auto pos = s.find("test");
        std::cout << s << "  " << pos << std::endl;

输出

i will test find test  7

2、rfind使用

size_type rfind(const basic_string& __str, size_type __pos = 0)

返回值为字符串中最后一次找到子字符串str时的下标。pos为起始查找的位置。如果搜索失败,则返回std::string::npos。

		std::string s = "i will test find test";
        auto pos = s.rfind("test");
        std::cout << s << "  " << pos << std::endl;

输出

i will test find test  17

3、substr使用

string substr (size_t pos = 0, size_t len = npos) const;

在字符位置pos开始,拷贝len个字符(或直到字符串的结尾)。

		std::string s = "i will test find test";
        std::string s2 = s.substr(2, 9);
        std::cout << s2 << std::endl;

输出

will test

配合find使用更佳

string substr (size_t pos = 0, size_t len = npos) const;

在字符位置pos开始,拷贝len个字符(或直到字符串的结尾)。

		std::string s = "i will test find test";
        auto pos = s.find("test");
        std::string s2 = s.substr(pos);
        std::cout << s2 << std::endl;

输出

test find test
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值