• 算法笔记-C++ string


    字符串输入

    中间无空格字符串接收

    
    // 方法一
    string s;
    cin>>s;
    
    // 方法二
    string t;
    t.resize(10); //必须设置大小
    scanf("%s", t.c_str());  //输入 123aaa
    cout<<t<<endl; //输出 123aaa 
    
    

    中间带空格字符串接收

    getline(cin, s);

    getline()和cin.getline()类似,但是cin.getline()属于istream流,而getline()属于string流,是不一样两个函数

    若getline(cin,str)前有cin<<a;那么影响geline,geline第一个读取到的将是cin输入a时缓存在缓存中的回车

    int n;
    string s;
    cin>>n;
    getchar();//吸收缓冲区中回车
    while(n-->0){
        getline(cin,s); //接收整行测试数据,整行中可以有多个空格
    }
    

    注: PAT常见问题中有说明:某些库函数因为存在安全隐患是不能用的,目前主要常见的是itoa和gets。

    字符串输出

    // 方法一
    string s="Hello World!";
    printf("%s",s.c_str());
    cout<<s<<endl;
    
    // 方法二
    char sc[13]="Hello World!";
    printf("%s", sc);
    cout<<sc<<endl;
    

    拼接

    字符串拼接数字

    /*
    	字符串拼接数字 
    */
    string st = "aaa";
    
    //error
    //st.append(11); 	//error need string
    //st.push_back(65); 	//success but 65='A'
    //cout<<st<<endl;	//aaaA 
    //st+=65;		//success but 65='A'
    //cout<<st<<endl;	//aaaAA
    
    // correct
    st+=to_string(11);
    cout<<st<<endl;
    st.append(1,9+'0');//在结尾追加一个字符'9'
    cout<<st<<endl;
    st.push_back(char(7+'0'));//在结尾追加一个字符'7'
    

    字符串拼接字符

    /*
    	字符串拼接字符 
    */
    string str = "aaa";
    str+='A';
    cout<<str<<endl;//aaaA
    
    str.push_back('B'); 
    cout<<str<<endl;//aaaAB
    
    //str.append('B'); //error 
    str.append(3, 'C');
    cout<<str<<endl;//aaaABCCC
    

    字符串拼接字符串

    /*
    	字符串拼接字符串 
    */
    string s = "aaa";
    s.append("bbb");
    cout<<s<<endl;//aaabbb
    
    s+="ccc";
    cout<<s<<endl;//aaabbbccc
    
    //	s.push_back("ddd");//error, need char 
    

    查找

    查找子串

    函数返回值 函数名(参数列表)
    string (1) size_t find (const string& str, size_t pos = 0) const noexcept;
    c-string (2) size_t find (const char* s, size_t pos = 0) const;
    buffer (3) size_t find (const char* s, size_t pos, size_type n) const;
    character (4) size_t find (char c, size_t pos = 0) const noexcept;
    #include <iostream>
    using namespace std;
    int main(int argc,char * argv[]) {
    	string s = "There are two needles in this haystack with needles.";
    	string s2 = "needle";
               
    	size_t found = s.find(s2); //查找子串,返回首字符出现位置
    	if (found!=string::npos)
    		std::cout << "first 'needle' found at: " << found << '
    ';
    
    	found=s.find("needles are small",found+1,6); //参数说明:子串,原串其实匹配位置,需匹配的子串长度
    	if (found!=string::npos)
    		std::cout << "second 'needle' found at: " << found << '
    ';
    
    	found=s.find("haystack"); //查找子串,返回首字符出现位置
    	if (found!=string::npos)
    		std::cout << "'haystack' also found at: " << found << '
    ';
    
    	found=s.find('.'); //查找字符,返回首次出现位置
    	if (found!=string::npos)
    		std::cout << "Period found at: " << found << '
    ';
    
    	// let's replace the first needle:
    	s.replace(s.find(s2),s2.length(),"preposition"); //替换第一个找到的s2所在位置,s2长度个字符
    	std::cout << s << '
    ';
    
    	return 0;
    }
    

    子串擦除

    // string::erase
    #include <iostream>
    #include <string>
    
    int main ()
    {
      std::string str ("This is an example sentence.");
      std::cout << str << '
    ';
                                               // "This is an example sentence."
      str.erase (10,8);                        //            ^^^^^^^^
      std::cout << str << '
    ';
                                               // "This is an sentence."
      str.erase (str.begin()+9);               //           ^
      std::cout << str << '
    ';
                                               // "This is a sentence."
      str.erase (str.begin()+5, str.end()-9);  //       ^^^^^
      std::cout << str << '
    ';
                                               // "This sentence."
      return 0;
    }    
    

    字符/字符串插入

    // inserting into a string
    #include <iostream>
    #include <string>
    
    int main ()
    {
      std::string str="to be question";
      std::string str2="the ";
      std::string str3="or not to be";
      std::string::iterator it;
    
      // used in the same order as described above:
      str.insert(6,str2);                 // to be (the )question
      str.insert(6,str3,3,4);             // to be (not )the question
      str.insert(10,"that is cool",8);    // to be not (that is )the question
      str.insert(10,"to be ");            // to be not (to be )that is the question
      str.insert(15,1,':');               // to be not to be(:) that is the question
      it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question
      str.insert (str.end(),3,'.');       // to be, not to be: that is the question(...)
      str.insert (it+2,str3.begin(),str3.begin()+3); // (or )
    
      std::cout << str << '
    ';
      return 0;
    }
    

    数值型字符串转换为数值

    将数字转换为字符串

    • to_string

    将字符串转换为整数(a开头的函数,需要将string转换为char * , string.c_str())

    • atof(字符数组):将字符串转换为双精度浮点型值。
    • atoi(字符数组):将字符串转换为整型值。
    • atol(字符数组):将字符串转换为长整型值。
    • strtol(字符串,结束位置,进制):结束位置若为结尾则为NULL,进制默认0为十进制
    • stoi(字符串):将字符串转换为int
    • stof(字符串):将字符串转换为浮点数
    • stod(字符串):将字符串转换为双精度浮点数
    cout<<"----------字符串与数字转换-------------"<<endl;
    
    cout<<"----------字符串->>int整数转换-------------"<<endl;
    //有效转换长度为10位
    string si = "1234";
    cout<<atoi(si.c_str())<<endl; //1234
    cout<<stoi(si)<<endl;  //1234
    cout<<stoi(si.c_str())<<endl; //1234
    
    cout<<"----------字符串->>long整数转换-------------"<<endl;
    string si0 = "2147483645";
    cout<<strtol(si0.c_str(),NULL,0)<<endl; //2147483645
    string sil = "214748364888";
    cout<<strtol(sil.c_str(),NULL,0)<<endl; //2147483647 超过最大值后,按最大值输出
    
    cout<<"----------字符串->>浮点数转换-------------"<<endl;
    string sid = "1234.231235678";
    cout<<atof(sid.c_str())<<endl; //1234
    cout<<stof(sid)<<endl; //1234.23
    cout<<stod(sid)<<endl;  //1234.23
    cout<<stod(sid.c_str())<<endl; //1234
    
    cout<<"----------浮点数->>字符串转换-------------"<<endl;
    double d = 1234.1234;
    cout<<to_string(d) <<endl;
    
    cout<<"----------整数数->>字符串转换-------------"<<endl;
    int in = 2147483647;
    cout<<to_string(in)<<endl;
    long lg = 2147483648;
    cout<<to_string(lg)<<endl; //-2147483648
    

    字符串模式匹配

    sscanf和sprintf

    适用场景

    输入一组数据,从数据中筛选出符合格式的数字或字符串进行其他处理

    sscanf 将字符串a格式化到temp变量中,如果不是double类型也有数据,但是sprintf后格式不匹配为0.00

    %lf换成%f不可以,因为%f接收的是float型数据,而temp是double型数据

    sprintf 将temp格式化到字符串b中,如果不是double型,b匹配不成功为0;

    如果类型不符,b为0.00;比如sscanf接收 aab1234.12,temp有值,但是sprintf输出为0.00
    如有小数点后位数大于格化式要求,b匹配时会四舍五入;

    代码

    #include <iostream>
    #include <string>
    using namespace std;
    int main() {
    	char a[50], b[50];
    	scanf("%s", a);
    	double temp;
    	/*
    	sscanf 将字符串a格式化到temp变量中,如果不是double类型也有数据,但是sprintf后格式不匹配会输出0.00
    			%lf换成%f不可以,因为%f接收的是float型数据,而temp是double型数据
    	sprintf 将temp格式化到字符串b中,如果不是double型,b匹配不成功为0;
    			如果类型不符,b为0.00;比如sscanf接收 aab1234.12,temp有值,但是sprintf输出为0.00
    			如有小数点后位数大于格化式要求,b匹配时会四舍五入;
    
    	*/
    	sscanf(a, "%lf", &temp);
    	sprintf(b, "%.2f",temp);
    
    	cout<<"	a: "<<a<<endl;
    	cout<<"	b: "<<b<<endl;
    	cout<<"	temp: "<<temp<<endl;
    	return 0;
    }
    

    测试结果:

    abc1234.23
    a: abc1234.23
    b: 0.00
    temp: 2.61855e-322

    123.1234
    a: 123.1234
    b: 123.12
    temp: 123.123

    123.234
    a: 123.234
    b: 123.23
    temp: 123.234

    123.2345678
    a: 123.2345678
    b: 123.23
    temp: 123.235

    -23.12
    a: -23.12
    b: -23.12
    temp: -23.12

    abcsdasdf
    a: abcsdasdf
    b: 0.00
    temp: 2.61855e-322

    123.479
    a: 123.479
    b: 123.48
    temp: 123.479

    字符数组

    字符数组长度获取

    strlen

    • 1 strlen 是一个函数,它用来计算指定字符串 str 的长度,但不包括结束字符(即 null 字符)
    • 2 #include 或 #include <string.h>。中没有
    #include <cstring>
    char a[40];
    int alen = strlen(a);
    

    strlen和sizeof的区别

    This should not be confused with the size of the array that holds the string. For example:

    char mystr[100]="test string";
    

    defines an array of characters with a size of 100 chars, but the C string with which mystr has been initialized has a length of only 11 characters. Therefore, while sizeof(mystr) evaluates to 100, strlen(mystr) returns 11.

  • 相关阅读:
    windows安装kafka
    excel打开utf-8的csv乱码
    laravel 记录慢sql日志
    php ftp连接的坑
    公用辅助方法
    ubuntu重置网络配置
    php socket
    docker ftp配置多个用户
    php aes-ecb-128位加密
    redis集群 哨兵模式
  • 原文地址:https://www.cnblogs.com/houzm/p/13370074.html
Copyright © 2020-2023  润新知