zoukankan      html  css  js  c++  java
  • C++STL string

    string的初始化

    string();

    string(const string &str);

    string(const char* str);

    string(int n,char c);

    遍历

    1.数组方式(重载数组)

    2.迭代器string::iterator

    3.ai()能抛出异常 

    string s1 = "123";
    
    char c;
    
    try
    
    {
    
    for(int i = 0;i < s1.length(),i++)
    
    {
    
      c = s1.at(i);//能抛出异常
    
    }
    
    }catch(...)
    
    {
    
    }
    

    字符指针和string的转换

    //string转char*
    string s1 = "aaa";
    char* p1 = (char*)s1.c_str();//或s1.data()
    //char*转string
    string s2;
    char* p2 = "qqq";
    s2 = p2;
    //string copy到buf
    char buf[1024];
    s1.copy(buf,3/*copy几个字符*/,0/*从哪个字符开始*/);
    

    连接

    1.使用重载+=

    string s1 = "111";

    string s2 = "222";

    string s3 = s1+s2;

    2.append

    string s3 = "333";

    string s4 = "444";

    s3.append(s4);

    查找和替换

    1.查找

    int find(char c ,int pos);//从pos查找c所在当前字符串的位置  

    int find(const char* s,int pos);//从pos开始查找字符串s在当前字符串的位置

    int find(const strin&* s,int pos);//从pos开始查找字符串s在当前字符串的位置

    如果查找不到返回-1

    int rfind(char c ,int pos);//从pos开始从后向前查找c所在当前字符串的位置  

    int rfind(const char* s,int pos);

    int rfind(const strin&* s,int pos);

    2.替换

    string &replace(int pos,int n,const char* s);//删除从pos开始的n个字符,然后在pos处插入s

    string &replace(int pos,int n,const string& s);//删除从pos开始的n个字符,然后在pos处插入s

    截断和插入

    1.删除

    string &erase(int pos ,int n);//删除pos开始的n个字符,返回修改后的字符串

    2.插入

    string &insert(int pos,const char* s);//在pos位置插入s

    string &insert(int pos,const string& s);//在pos位置插入s

    string &insert(int pos,int n,char c);//在pos位置插入n个c

    string算法

    string s1 = "AAAbbb";

    transform(s1.begin(),s1.end(),s1.begin(),toupper);//转化成大写

    transform(s1.begin(),s1.end(),s1.begin(),tolower);//转化成小写

  • 相关阅读:
    Linux任务调度
    用户管理——用户和用户组
    Linux实用指令
    spring模拟ioc
    浅谈log4j-3-不同输出样式
    浅谈log4j-2
    浅谈log4j
    windows下安装kibana
    【PHP】 解决报错:Error: php71w-common conflicts with php-common-5.4.16-43.el7_4.x86_64
    mysql 8.0设置日期为0000-00-00 00:00:00时报错
  • 原文地址:https://www.cnblogs.com/smh2015/p/9634419.html
Copyright © 2011-2022 走看看