C++ 函数
#include <string>
Functions:
stod
stof
stoi
stol
stold
stoll
stoul
stoull
to_string
to_wstring
Iterators:
begin() end()
在迭代string的时候,string::iterator中iterator一定要有。
还以不这么复杂,直接用auto,如auto rit=str.rbegin();
- // string::begin/end
- #include <iostream>
- #include <string>
- int main ()
- {
- std::string str ("Test string");
- for ( std::string::iterator it=str.begin(); it!=str.end(); ++it)
- std::cout << *it; //使用 * 访问迭代器所指向的元素
- std::cout << '\n';
- return 0;
- }
rbegin() rend()
在反向迭代string的时候,string::reverse_iterator中reverse_iterator一定要有。
还以不这么复杂,直接用auto,如auto rit=str.rbegin();
- // string::rbegin/rend
- #include <iostream>
- #include <string>
- int main ()
- {
- std::string str ("now step live...");
- for (std::string::reverse_iterator rit=str.rbegin(); rit!=str.rend(); ++rit)
- std::cout << *rit; //使用 * 访问迭代器所指向的元素
- return 0;
- }
cbegin
Return const_iterator to beginning (public member function )
cend
Return const_iterator to end (public member function )
crbegin
Return const_reverse_iterator to reverse beginning (public member function )
crend
Return const_reverse_iterator to reverse end (public member function )
Capacity:
size
Return length of string (public member function )
length
Return length of string (public member function )
clear
Clear string (public member function )
empty
Test if string is empty (public member function )
max_size
Return maximum size of string (public member function )
capacity
Return size of allocated storage (public member function )
reserve
Request a change in capacity (public member function )
resize
Resize string (public member function )
void resize (size_t n);
void resize (size_t n, char c);
shrink_to_fit
Shrink to fit (public member function )
Element access:
operator[]
Get character of string (public member function )
字符串string 可以像数组一样被使用:str[1] ,定位一个字符
at
Get character in string (public member function )
back
Access last character (public member function )
str.back() = ‘!’;是对最后一个字符的引用。此函数不能用于空字符串。
front
Access first character (public member function )
Modifiers:
operator+=
Append to string (public member function )
append
Append to string (public member function )
push_back
Append character to string (public member function )
assign (有 8种用法)
Assign content to string (public member function )
有8种使用形式
将原来string中的字符全都置换掉
- // string::assign
- #include <iostream>
- #include <string>
- using namespace std;
- int main ()
- {
- string str;
- string base="The quick brown fox jumps over a lazy dog.";
- // used in the same order as described above:
- str.assign(base);
- cout << str << '\n';
- str.assign(base,10,9);
- cout << str << '\n'; // "brown fox"
- str.assign(base,10);
- cout << str << '\n'; // "brown fox jumps over a lazy dog."
- str.assign("pangrams are cool",7);
- cout << str << '\n'; // "pangram"
- str.assign("c-string");
- cout << str << '\n'; // "c-string"
- str.assign(10,'*');
- cout << str << '\n'; // "**********"
- str.assign<int>(10,0x2D);
- cout << str << '\n'; // "----------"
- str.assign(base.begin()+16,base.end()-12);
- cout << str << '\n'; // "fox jumps over"
- return 0;
- }
insert (有 8种用法)
Insert into string (public member function )
有 8种用法
在原来string中插入字符
- // 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; //下面 迭代器it 指向的是str中的逗号位置。
- // 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(...)
- //在迭代器i表示的位置前面插入一段字符,从start开始,以end结束.
- str.insert (it+2,str3.begin(),str3.begin()+3); // (or )
- std::cout << str << '\n';
- return 0;
- }
erase (有 5种用法)
Erase characters from string (public member function )
有 5种用法
- // string::erase
- #include <iostream>
- #include <string>
- using namespace std;
- int main (){
- string str ("This is an example sentence.");
- cout << str << '\n';
- str.erase (10,8); // "This is an example sentence."
- cout << str << '\n'; // ^^^^^^^^
- // str.begin()+9 是迭代器指向的数据,只会删除一个字符
- str.erase (str.begin()+9); // "This is an sentence."
- cout << str << '\n'; // ^
- str.erase (str.begin()+5, str.end()-9); // "This is a sentence."
- cout << str << '\n'; // ^^^^^
- // "This sentence."
- string s("Well, have all the donuts in the world!");
- cout << "The original string is '" << s << "'" << endl;
- //5 位置指向,删除5位置后的所有字符
- s.erase( 5 );
- cout << "Now the string is '" << s << "'" << endl;
- s.erase();
- cout << "Now the string is '" << s << "'" << endl;
- return 0;
- }
replace (两种:根据位置,根据迭代器)
Replace portion of string (public member function )
两种:根据位置,根据迭代器
指定原来string中的一些位置上的字符,进行置换掉
- // replacing in a string
- #include <iostream>
- #include <string>
- int main ()
- {
- std::string base="this is a test string.";
- std::string str2="n example";
- std::string str3="sample phrase";
- std::string str4="useful.";
- // replace signatures used in the same order as described above:
- // Using positions: 0123456789*123456789*12345
- std::string str=base; // "this is a test string."
- str.replace(9,5,str2); // "this is an example string." (1)
- str.replace(19,6,str3,7,6); // "this is an example phrase." (2)
- str.replace(8,10,"just a"); // "this is just a phrase." (3)
- str.replace(8,6,"a shorty",7); // "this is a short phrase." (4)
- str.replace(22,1,3,'!'); // "this is a short phrase!!!" (5)
- // Using iterators: 0123456789*123456789*
- str.replace(str.begin(),str.end()-3,str3); // "sample phrase!!!" (1)
- str.replace(str.begin(),str.begin()+6,"replace"); // "replace phrase!!!" (3)
- str.replace(str.begin()+8,str.begin()+14,"is coolness",7); // "replace is cool!!!" (4)
- str.replace(str.begin()+12,str.end()-4,4,'o'); // "replace is cooool!!!" (5)
- str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());// "replace is useful." (6)
- std::cout << str << '\n';
- return 0;
- }
swap
Swap string values (public member function )
std::string buyer ("money");
std::string seller ("goods");
seller.swap (buyer);
pop_back
Delete last character (public member function )
std::string str ("hello world!");
str.pop_back();
String operations:
c_str
Get C string equivalent (public member function )
将string转换成字符串数组,在末尾加上一个额外的终止空字符('\0')
- // strings and c-strings
- #include <iostream>
- #include <cstring>
- #include <string>
- int main ()
- {
- std::string str ("Please split this sentence into tokens");
- char * cstr = new char [str.length()+1]; //将string转换成字符串数组,末尾有\0
- std::strcpy (cstr, str.c_str());
- // cstr now contains a c-string copy of str
- char * p = std::strtok (cstr," ");
- while (p!=0){
- std::cout << p << '\n';
- p = std::strtok(NULL," ");
- }
- delete[] cstr;
- return 0;
- }
- Output:
- Please
- split
- this
- sentence
- into
- tokens
data
Get string data (public member function )
data()和c_str()都是用来获取底层字符串的首地址的,但是在C++98中规定的是data()返回的字符串不保证有结尾\0,但是c_str()返回的字符串保证有结尾\0,也就是C++98标准在设计字符串的时候是想抛弃C风格的字符串语法的,但是在实际应用中,往往需要将C++的string转换为C风格的字符串const char*。
这一点平常使用的时候没问题,但如果想直接通过C风格的接口修改string中的内容就麻烦了,因为&str[0]返回的字符串并不保证有结尾'\0'
get_allocator
Get allocator (public member function )
copy
Copy sequence of characters from string (public member function )
函数不会在复制内容的末尾追加空字符,
这个函数在用的时候有点区别,中间的参数代表 长度,第三个参数代表 起始位置
size_t copy (char* s, size_t len, size_t pos = 0) const;
- // string::copy
- #include <iostream>
- #include <string>
- int main ()
- {
- char buffer[20];
- std::string str ("Test string...");
- std::size_t length = str.copy(buffer,6,5);
- buffer[length]='\0';
- std::cout << "buffer contains: " << buffer << '\n';
- return 0;
- }
- Output:
- buffer contains: string
find
Find content in string (public member function )
- // string::find
- #include <iostream> // std::cout
- #include <string> // std::string
- int main () {
- std::string str ("There are two needles in this haystack with needles.");
- std::string str2 ("needle");
- // different member versions of find in the same order as above:
- std::size_t found = str.find(str2);
- if (found!=std::string::npos)
- std::cout << "first 'needle' found at: " << found << '\n';
- //这个例子 比较特殊,参数found 是第一次查找的结果值。
- //而且 第三个参数 6 是指"needles are small"的,前六个字符。
- found=str.find("needles are small",found+1,6);
- if (found!=std::string::npos)
- std::cout << "second 'needle' found at: " << found << '\n';
- found=str.find("haystack");
- if (found!=std::string::npos)
- std::cout << "'haystack' also found at: " << found << '\n';
- found=str.find('.');
- if (found!=std::string::npos)
- std::cout << "Period found at: " << found << '\n';
- // let's replace the first needle:
- str.replace(str.find(str2),str2.length(),"preposition");
- std::cout << str << '\n';
- return 0;
- }
- Notice how parameter pos is used to search for a second instance of the same search string. Output:
- first 'needle' found at: 14
- second 'needle' found at: 44
- 'haystack' also found at: 30
- Period found at: 51
- There are two prepositions in this haystack with needles.
rfind
Find last occurrence of content in string (public member function )
find_first_of
Find character in string (public member function )
find_last_of
Find character in string from the end (public member function )
在字符串中搜索 与 参数中指定的 任意字符匹配的最后一个字符。
- // string::find_last_of
- #include <iostream> // std::cout
- #include <string> // std::string
- #include <cstddef> // std::size_t
- void SplitFilename (const std::string& str)
- {
- std::cout << "Splitting: " << str << '\n';
- std::size_t found = str.find_last_of("/\\");
- std::cout << " path: " << str.substr(0,found) << '\n';
- std::cout << " file: " << str.substr(found+1) << '\n';
- }
- int main ()
- {
- std::string str1 ("/usr/bin/man");
- std::string str2 ("c:\\windows\\winhelp.exe");
- SplitFilename (str1);
- SplitFilename (str2);
- return 0;
- }
- Splitting: /usr/bin/man
- path: /usr/bin
- file: man
- Splitting: c:\windows\winhelp.exe
- path: c:\windows
- file: winhelp.exe
find_first_not_of
Find absence of character in string (public member function )
Searches the string for the first character that does not match any of the characters specified in its arguments.
- / string::find_first_not_of
- #include <iostream> // std::cout
- #include <string> // std::string
- #include <cstddef> // std::size_t
- int main ()
- {
- std::string str ("look for non-alphabetic characters...");
- //是和"abcdefghijklmnopqrstuvwxyz "中每一个字符比较,不把这个看成字符串
- std::size_t found = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");
- if (found!=std::string::npos) {
- std::cout << "The first non-alphabetic character is " << str[found];
- std::cout << " at position " << found << '\n';
- }
- return 0;
- }
- The first non-alphabetic character is - at position 12
- .
find_last_not_of
Find non-matching character in string from the end (public member function )
substr (两种用法,一种当中截取一段字符,一种根据pos截取到str结尾)
Generate substring (public member function )
两种用法,一种当中截取一段字符,一种根据pos截取到str结尾
- // string::substr
- #include <iostream>
- #include <string>
- int main (){
- std::string str="We think in generalities, but we live in details.";
- // (quoting Alfred N. Whitehead)
- std::string str2 = str.substr (3,5); // "think"
- std::size_t pos = str.find("live"); // position of "live" in str
- std::string str3 = str.substr (pos); // get from "live" to the end
- std::cout << str2 << ' ' << str3 << '\n';
- return 0;
- }
- Output:
- think live in details.
- .
compare
Compare strings (public member function )
- // comparing apples with apples
- #include <iostream>
- #include <string>
- int main ()
- {
- std::string str1 ("green apple");
- std::string str2 ("red apple");
- if (str1.compare(str2) != 0)
- std::cout << str1 << " is not " << str2 << '\n';
- // 6是str1的pos , 5 是str1的len.
- if (str1.compare(6,5,"apple") == 0)
- std::cout << "still, " << str1 << " is an apple\n";
- // str2.size()-5是str2的pos , 5 是str2的len.
- if (str2.compare(str2.size()-5,5,"apple") == 0)
- std::cout << "and " << str2 << " is also an apple\n";
- if (str1.compare(6,5,str2,4,5) == 0)
- std::cout << "therefore, both are apples\n";
- return 0;
- }
- Output:
- green apple is not red apple
- still, green apple is an apple
- and red apple is also an apple
- therefore, both are apples
- .
Member constants
npos
Maximum value for size_t (public static member constant )
Non-member function overloads
operator+
Concatenate strings (function )
relational operators
Relational operators for string (function )
swap
Exchanges the values of two strings (function )
operator>>
Extract string from stream (function )
operator<<
Insert string into stream (function )
getline
Get line from stream into string (function )
3、cin >> 、 cin.getline() 、cin.get()
cin.get(),cin.getline() 是C++的
cin.get()获取一个字符
cin.getline() 获取一行字符串
getline(cin,s)是C的,获取一行字符串
- #include <iostream>
- #include <stdio.h>
- #include <string>
- #include <string.h>
- using namespace std;
- int main(){
- char data[100];
- char tat[50];
- char cmd[2];
- while(1){
- cout << "cin the cmd:";
- cin >> cmd;
- string str="\n";
- getline(cin,str); //将 回车符 作为输入流cin以清除缓存
- cout << "cmd is:" << cmd <<endl;
- cout << "getline str is:" << str <<endl;
- if(strcmp(cmd , "Y")==0){
- cout << "Enter your name: ";
- cin.get(data, 100);//cin.getline(data,100); //getline输入超范围,程序会出错,get()不会导致程序出错。但是多余的数据在输入缓存中。
- cin.clear(); //cin.get()如果没输入,直接Enter,会发生错误
- cin.ignore(1024,'\n'); // 清除 在输入缓存中 多余的数据
- cout << " : " << data << endl;
- }
- else if(strcmp(cmd , "N")==0){
- break;
- }
- else {
- cout << "again" << endl;
- }
- }
- return 0;
- }
cin >>
cin是C++中最常用的输入语句,当遇到空格或者回车键即停止
缺点:只能输入没有空格的字符串,当输入中含有空格,则只能输出空格之前的字符
当同时使用cin>>,getline()时,需要注意的是,在cin>>输入流完成之后,getline()之前,需要通过
str="\n"; getline(cin,str);
的方式将回车符作为输入流cin以清除缓存,如果不这样做的话,在控制台上就不会出现getline()的输入提示,而直接跳过,因为程序默认地将之前的变量作为输入流。
cin.getline()
cin.getline()属于istream流,而getline()属于string流,是不一样的两个函数
用法:接收一行字符串,可以接收空格并输出,可以控制接受的字符范围
延伸:
1、cin.getline()实际上有三个参数,cin.getline(接收字符串的变量,接收字符个数,结束字符)
2、当第三个参数省略时,系统默认为'\0'
3、如果将例子中cin.getline()改为cin.getline(m,5,'a');当输入jlkjkljkl时输出jklj,输入jkaljkljkl时,输出jk
cin.getline()与 cin.get(array_name,Arsize)的读取方式差不多,以Enter结束,可以接受空格字符。按照长度(Arsize)读取字符, 会丢弃最后的Enter字符。
但是这两个函数是有区别的:cin.get(array_name, Arsize)当输入的字符串超长时,不会引起cin函数的错误,后面的cin操作会继续执行,只是直接从缓冲区中取数据。但是cin.getline()当输入超长时,会引起cin函数的错误,后面的cin操作将不再执行。
getline()
cin.getline()属于istream流,而getline()属于string流,是不一样的两个函数
用法:接收一行字符串,可以接收空格并输出,需包含“#include<string>”
add
1、sizeof() 与 strlen()
-
char *str1 = "asdfgh";
-
char str2[] = "asdfgh";
-
char str3[8] = {'a', 's', 'd'};
-
char str4[] = "as\0df";
-
执行结果是:
-
sizeof(str1) = 4; strlen(str1) = 6;
-
sizeof(str2) = 7; strlen(str2) = 6;
-
sizeof(str3) = 8; strlen(str3) = 3;
-
sizeof(str4) = 6; strlen(str4) = 2;
str1是字符指针变量,sizeof 获得的是该指针所占的地址空间,32 位操作系统对应 4 字节,所以结果是 4;strlen 返回的是该字符串的长度,遇到 \0 结束, \0 本身不计算在内,故结果是 6。
str2 是字符数组,大小由字符串常量 "asdfgh" 确定,sizeof 获得该数组所占内存空间大小,包括字符串结尾的 \0 ,所以结果为 7;strlen 同理返回 6。
str3 也是字符数组,但大小确定为 8,故 sizeof 得到的结果是 8;strlen 统计 \0 之前所有字符的个数,即为 3;
str4 是常量字符数组,sizeof 得到字符总数即 6;strlen 计算至 \0 结束,因此返回 2;
总结一句就是 sizeof 计算的是变量的大小,而 strlen 计算的是字符串的长度,前者不受字符 \0 影响,后者以 \0 作为长度判定依据。
4、char* str 与 string 互换
在C++中,
char* p = "abc"; // valid in C, invalid in C++
会跳出警告:warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
改成下面会通过warning
char* p = (char*)"abc"; // OK
或者改成下面:
char const *p = "abc"; // OK
5、list()
- struct ass_header_listnode{ //先定义一个可用的 listnode
- char* key;
- char* value;
- ass_header_listnode *next;
- ass_header_listnode(char *str1 , char *str2, ass_header_listnode *nextl = nullptr){ //结构体的构造函数
- key = str1;
- value = str2;
- next = nextl;
- }
- };
- // 添加 listnode
- ass_header_listnode *events = new ass_header_listnode((char*)"Text",(char*)"text");
- events = new ass_header_listnode((char*)"Effect" , (char*)"Scroll up", events);
- events = new ass_header_listnode((char*)"MarginV", (char*)"0", events);
- //遍历 查找元素
- ass_header_listnode *ptr_temp = events;
- ptr_location_flag = events;
- while(ptr_temp != nullptr){
- if(strcmp(ptr_temp->key , "Effect") == 0){
- ptr_location_flag = ptr_temp;
- break;
- }
- cout << "check ptr_temp->key: " << ptr_temp->key << endl;
- ptr_temp = ptr_temp->next;
- }
2、map()
使用map得包含map类所在的头文件
#include <map> //注意,STL头文件没有扩展名.h map对象是模板类,需要关键字和存储对象两个模板参数:
std:map <int,string> personnel; //这样就定义了一个用int作为索引,并拥有相关联的指向string的指针.
为了使用方便,可以对模板类进行一下类型定义,
typedef map <int,CString> UDT_MAP_INT_CSTRING;
UDT_MAP_INT_CSTRING enumMap;
数据的插入
- //数据的插入
- map<int, string> mapStudent;
- //第一种:用insert函数插入pair数据
- mapStudent.insert(pair<int, string>(1, "student_one"));
- //第二种:用insert函数插入value_type数据
- mapStudent.insert(map<int, string>::value_type (2, "student_two"));
- //第三种:用数组方式插入数据
- mapStudent[3] = "student_three";
数据的遍历
-
map<string , string>::iterator itBegin;
-
map<string , string>::iterator itEnd;
-
itBegin = v4_styles.begin();
-
itEnd = v4_styles.end();
-
while(itBegin != itEnd){
-
ret_format = ret_format.append(itBegin->first); //获取map中的 key值
-
ret_format = ret_format.append(",");
-
ret_style = ret_style.append(itBegin->second); //获取map中的value值
-
ret_style = ret_style.append(",");
-
itBegin++;
-
}
反向迭代器
std::map < int, string > ::reverse_iterator iter;
for(iter = mapPerson.rbegin(); iter != mapPerson.rend(); iter++)
cout<<iter->first<<" "<<iter->second<<endl;
查找并获取map中的元素
map中的元素是自动按Key升序排序,所以不能对map用sort函数;
- map<string , string> v4_styles;
- v4_styles.insert(pair<string , string>("Name" ,"Default"));
- map<string , string>::iterator l_it;
- l_it = v4_styles.find("Name"); // 这里没有用循环语句
- if(l_it != v4_styles.end()){
- cout<<"Find it"<<endl;
- }
- else {
- cout<<"ERROR: not find !"<<endl;
- }
map中删除元素
移除某个map中某个条目用erase()
该成员方法的定义如下:
iterator erase(iterator it);//通过一个条目对象删除
iterator erase(iterator first,iterator last)//删除一个范围
size_type erase(const Key&key);//通过关键字删除
clear()就相当于enumMap.erase(enumMap.begin(),enumMap.end());
这里要用到erase函数,它有三个重载了的函数,下面在例子中详细说明它们的用法
- #include <map>
- #include <string>
- #include <iostream>
- using namespace std;
- int main(){
- map<int, string> mapStudent;
- mapStudent.insert(pair<int, string>(1, "student_one"));
- mapStudent.insert(pair<int, string>(2, "student_two"));
- mapStudent.insert(pair<int, string>(3, "student_three"));
- //如果你要演示输出效果,请选择以下的一种,你看到的效果会比较好
- //如果要删除1,用迭代器删除
- map<int, string>::iterator iter;
- iter = mapStudent.find(1);
- mapStudent.erase(iter);
- //如果要删除1,用关键字删除
- int n = mapStudent.erase(1);//如果删除了会返回1,否则返回0
- //用迭代器,成片的删除
- //一下代码把整个map清空
- mapStudent.erase( mapStudent.begin(), mapStudent.end() );
- //成片删除要注意的是,也是STL的特性,删除区间是一个前闭后开的集合
- }