c++ string

xiaoxiao2022-06-11  34

c++ string
#include <iostream> #include<string> using namespace std; int main(int argc, char *argv[]) { //1.生成字符串和赋值的过程函数 char *p="hello ,good morning"; string str;//生成一个空的字符串 str= "tell me you love the world"; string s01(p); string s02(str);//拷贝构造函数生成的str的复制品 string s03(p,5);//s03="hello" string s04(str,12,15);//s04="love the world" string s05(10,'c');//s05="cccccccccc" //2.字符串操作函数 //2.1 C++和c的字符串的转换 const char *p1=str.data();//return 字符数组,但是在末尾不加\0 const char *p2=str.c_str();//return 字符数组,但是在末尾加\0 //2.2 大小和容量 int size1=str.length(); //size()=length() str.reserve(16); //按理说size=16的,但是没有 //2.3元素存取 str.at(17); str[17]; //2.4比较函数 string s("abcd"); s.compare("abcd"); //返回0 s.compare("dcba"); //返回一个小于0的值 s.compare("ab"); //返回大于0的值 s.compare(s); //相等 s.compare(0,2,s,2,2); //用”ab”和”cd”进行比较 小于零 s.compare(1,2,"bcx",2); //用”bc”和”bc”比较。 //2.5更改内容(assign,append,insert,replace,erase) s.assign(str,0,4);//s="tell" s.assign(str,0,string::npos);//s=tell me you love the world s.assign("hell",4);//s=hell //s.append(str,0,4);//s=helltell //s.append(str,0,string::npos);//s=hell+str //s.append("hell",4);//s=hellhell s.append(5,'c');//s=hellccccc s.insert(0,"my name"); s.insert(1,str); s.replace(1,2,"nternationalizatio");//从索引1开始的2个替换成后面的C_string s.erase(13);//从索引13开始往后全删除 s.erase(7,5);//从索引7开始往后删5个 //2.6查找s.find(搜索内容,[搜索起点],[搜索字符串的个数]) ,返回第一个字符的索引 s="hello the world"; cout<<s.find("the",0,1);//return 6 //2.7子字符串substr s.substr();//返回s的全部内容 s.substr(11);//从索引11往后的子串 s.substr(5,6);//从索引5开始6个字符 /* * 数据类型不外乎容量大小,比较,查找,截取子部分,数据操作(添加,删除,插入,取代) */ return 0; }
转载请注明原文地址: https://www.6miu.com/read-4931535.html

最新回复(0)