String

  • 头文件

#include <string>
using namespace std;


  • 定义

string str;
//如果要初始化
string str = "abcd";


  • 访问   
(1)下标访问
printf("%c", str[i]);

     string str2;
     scanf("%s", str2.c_str());  // == cin >> str2     //不要用scanf
     printf("%s\n", str2.c_str());  // == cout << str2;
2. 迭代器 :  string::iterator it;    //类似指针 通过 *it 来访问   it可以 it++         能*(it + i)only  vector and string can do this
string::iterator it = vi.begin();      //vi.begin() and vi.end() is one of iterator

for(string::iterator it = str.begin(); it != str.end(); it++) {
    printf("%c ", *(it + i)) ;     //output str[i];
}

so str[i] and *(str.begin() + i) are equivalent


  • Common functions:

(1)  operator+=             //这是string的加法,可以将两个string直接拼接起来

(2)  compare operator (==、 !=、 <、 <=、 >、>=)     // 比较大小  规则是字典序

(3)  length() / size()                         //返回string的长度                        O(1)

(4)  insert(pos, string)                         //在pos位置插入字符串string (string变量或"")
      insert(it, it2, it3)                        //it为原来字符串欲插入位置, it2和it3为带插入字符串首位的迭代器   用来表示串[it2, it3) 将被插在it的位置上

(5)  erase(it)                     //删除迭代器it位置的元素
      erase(first, last)          //删除迭代器 [ first, last ) 内的所有元素  参数都是 迭代器 
      erase(pos, length)     //pos是需要删除的起始位置, length为删除的字符个数    删除的位置为[pos, pos+length]

(6)  clear()                        //清空string    O(1)

(7)  substr(pos, len)                        // 返回从pos位置开始、长度为len的子串
string str = "Thank you for your smile."
cout <<str.substr(0, 5) << endl;
cout <<str.substr(14, 4) << endl;
cout <<str.substr(19, 5) << endl;

//output
Thank
your
smile

(8)  string::npos                //其实是一个常数-1 或 4294967295(unsigned_int) 因此可以认为是unsigned_int类型的最大值。用string::npos用以作为find()函数失配时的返回值 实例见find()
(9)  find(str2)                   //模式匹配,当str2是str的子串时,返回其在str中第一次出现的位置;  如果str2不是str的子串,那么返回string::npos
      find(str2, pos)            // 从str的pos位置开始模式匹配,返回值跟find(str2)相同
string str = "Thank you for your smiale.";
string str2 = "you";
string str3 = "me";

if(str.find(str2) != string::npos) {
    cout << str.find(str2) << endl;
}
if(str.find(str2) != string::npos) {
    cout << str.find(str2) << endl;
}
if(str.find(str2, 7) != string::npos) {             //从7位置开始找
    cout << str.find(str2) << endl;
}
if(str.find(str3) != string::npos) {
    cout << str.find(str2) << endl;
} else {
    cout << "no position" << endl;
}

(10)  replace(pos, len, str2)             //从str从pos位置开始, 长度为len的子串替换为 str2          替换范围 [pos, pos+len]
        replace(it1, it2, str2)                //把str的迭代器[it1, it2) 范围替换为str2                              替换范围 [it1, it2)

getline(cin,s6); 读取字符到遇到换行,空格可读入,知道‘\n’结束

  • 主要用途:
相当于Java中的包裹类,后有很多功能
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值