zoukankan      html  css  js  c++  java
  • 【C++札记】标准模板库string

    介绍

    c++中字符串string对象属于一个类,内置了很多实用的成员函数,操作简单,方便更直观。

    命名空间为std,所属头文件<string> 注意:不是<string.h>。

    跟进代码会发现string其实只是basic_string模板类的一个typedef。

    赋值

    	//方法1
    	string str1 = "woniu201";
    	//方法2
    	char* p = "woniu201";
    	string str2 = p;

    遍历

    	//方法1 使用下标
    	for (int i=0; i<str1.length(); i++)
    	{
    		printf("%c", str1[i]);
    	}
    	//方法2 使用迭代器
    	string::iterator it;
    	for (it=str1.begin(); it!=str1.end(); it++)
    	{
    		printf("%c", *it);
    	}

    查找

    	string str5 = "woniu201";
    	int pos1 = str5.find("n", 0);     //从位置0开始查找字符n在字符串str5中的位置
    	int pos2 = str5.find("niu", 0);   //从位置0开始查找字符串niu在字符串str5中的位置
    	int pos3 = str5.find("niu", 0, 2);//从位置0开始查找字符串niu前两个字符组成的字符串在str5中的位置

    截取

    	string str3 = "woniu201";
    	string str4 =  str3.substr(0,5);//返回从下标0开始的5个字符组成的字符串 

    其他

        //返回C串char* c_str()
        char buf[1024] = {0};
        string str5 = "i love chain";
        strcpy(buf, str5.c_str());	
    
        //字符串连接
    	string str6 = "woniu201";
    	string str7 = "hailuo201";
    	string str8 = str6 + str7;
    
    	//判断是否相等
    	bool bRet1 = (str6 == str7); //相等为true,否则为false
    
    	//判断字符串是否为空
    	bool bRet2 = str6.empty();
    
    	//字符串插入
    	string str9 = str6.insert(0, str7); //字符串str6的0位置插入字符串str7
    
    	//字符串交换
    	str6.swap(str7);
    
        //判断是否包含
        string::size_type idx = str6.find("woniu");
        if(idx == string::npos)
        {
            cout << "not found" << endl;
        }


    欢迎加群交流:C/C++开发交流

  • 相关阅读:
    C#如何通过NCO3.0来连接SAP并调用SAP中的RFC
    .Net连接到SAP【转载】
    将博客搬至CSDN
    Apache Flume 简介
    日志收集以及分析:Splunk
    《淘宝技术这十年》读后感
    python参考手册--第9章
    Hadoop将过时了?
    pythn BeautifulSoup
    Python性能鸡汤
  • 原文地址:https://www.cnblogs.com/woniu201/p/11694610.html
Copyright © 2011-2022 走看看