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();

  1. // string::begin/end
  2. #include <iostream>
  3. #include <string>
  4. int main ()
  5. {
  6. std::string str ("Test string");
  7. for ( std::string::iterator it=str.begin(); it!=str.end(); ++it)
  8. std::cout << *it; //使用 * 访问迭代器所指向的元素
  9. std::cout << '\n';
  10. return 0;
  11. }

rbegin() rend()

在反向迭代string的时候,string::reverse_iterator中reverse_iterator一定要有。

还以不这么复杂,直接用auto,如auto rit=str.rbegin();

  1. // string::rbegin/rend
  2. #include <iostream>
  3. #include <string>
  4. int main ()
  5. {
  6. std::string str ("now step live...");
  7. for (std::string::reverse_iterator rit=str.rbegin(); rit!=str.rend(); ++rit)
  8. std::cout << *rit; //使用 * 访问迭代器所指向的元素
  9. return 0;
  10. }

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中的字符全都置换掉

  1. // string::assign
  2. #include <iostream>
  3. #include <string>
  4. using namespace std;
  5. int main ()
  6. {
  7. string str;
  8. string base="The quick brown fox jumps over a lazy dog.";
  9. // used in the same order as described above:
  10. str.assign(base);
  11. cout << str << '\n';
  12. str.assign(base,10,9);
  13. cout << str << '\n'; // "brown fox"
  14. str.assign(base,10);
  15. cout << str << '\n'; // "brown fox jumps over a lazy dog."
  16. str.assign("pangrams are cool",7);
  17. cout << str << '\n'; // "pangram"
  18. str.assign("c-string");
  19. cout << str << '\n'; // "c-string"
  20. str.assign(10,'*');
  21. cout << str << '\n'; // "**********"
  22. str.assign<int>(10,0x2D);
  23. cout << str << '\n'; // "----------"
  24. str.assign(base.begin()+16,base.end()-12);
  25. cout << str << '\n'; // "fox jumps over"
  26. return 0;
  27. }

insert (有 8种用法)

Insert into string (public member function )

有 8种用法

在原来string中插入字符

  1. // inserting into a string
  2. #include <iostream>
  3. #include <string>
  4. int main ()
  5. {
  6. std::string str="to be question";
  7. std::string str2="the ";
  8. std::string str3="or not to be";
  9. std::string::iterator it; //下面 迭代器it 指向的是str中的逗号位置。
  10. // used in the same order as described above:
  11. str.insert(6,str2); // to be (the )question
  12. str.insert(6,str3,3,4); // to be (not )the question
  13. str.insert(10,"that is cool",8); // to be not (that is )the question
  14. str.insert(10,"to be "); // to be not (to be )that is the question
  15. str.insert(15,1,'😂; // to be not to be(😃 that is the question
  16. it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question
  17. str.insert (str.end(),3,'.'); // to be, not to be: that is the question(...)
  18. //在迭代器i表示的位置前面插入一段字符,从start开始,以end结束.
  19. str.insert (it+2,str3.begin(),str3.begin()+3); // (or )
  20. std::cout << str << '\n';
  21. return 0;
  22. }

erase (有 5种用法)

Erase characters from string (public member function )

有 5种用法

  1. // string::erase
  2. #include <iostream>
  3. #include <string>
  4. using namespace std;
  5. int main (){
  6. string str ("This is an example sentence.");
  7. cout << str << '\n';
  8. str.erase (10,8); // "This is an example sentence."
  9. cout << str << '\n'; // ^^^^^^^^
  10. // str.begin()+9 是迭代器指向的数据,只会删除一个字符
  11. str.erase (str.begin()+9); // "This is an sentence."
  12. cout << str << '\n'; // ^
  13. str.erase (str.begin()+5, str.end()-9); // "This is a sentence."
  14. cout << str << '\n'; // ^^^^^
  15. // "This sentence."
  16. string s("Well, have all the donuts in the world!");
  17. cout << "The original string is '" << s << "'" << endl;
  18. //5 位置指向,删除5位置后的所有字符
  19. s.erase( 5 );
  20. cout << "Now the string is '" << s << "'" << endl;
  21. s.erase();
  22. cout << "Now the string is '" << s << "'" << endl;
  23. return 0;
  24. }

replace (两种:根据位置,根据迭代器)

Replace portion of string (public member function )

两种:根据位置,根据迭代器

指定原来string中的一些位置上的字符,进行置换掉

  1. // replacing in a string
  2. #include <iostream>
  3. #include <string>
  4. int main ()
  5. {
  6. std::string base="this is a test string.";
  7. std::string str2="n example";
  8. std::string str3="sample phrase";
  9. std::string str4="useful.";
  10. // replace signatures used in the same order as described above:
  11. // Using positions: 0123456789*123456789*12345
  12. std::string str=base; // "this is a test string."
  13. str.replace(9,5,str2); // "this is an example string." (1)
  14. str.replace(19,6,str3,7,6); // "this is an example phrase." (2)
  15. str.replace(8,10,"just a"); // "this is just a phrase." (3)
  16. str.replace(8,6,"a shorty",7); // "this is a short phrase." (4)
  17. str.replace(22,1,3,'!'); // "this is a short phrase!!!" (5)
  18. // Using iterators: 0123456789*123456789*
  19. str.replace(str.begin(),str.end()-3,str3); // "sample phrase!!!" (1)
  20. str.replace(str.begin(),str.begin()+6,"replace"); // "replace phrase!!!" (3)
  21. str.replace(str.begin()+8,str.begin()+14,"is coolness",7); // "replace is cool!!!" (4)
  22. str.replace(str.begin()+12,str.end()-4,4,'o'); // "replace is cooool!!!" (5)
  23. str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());// "replace is useful." (6)
  24. std::cout << str << '\n';
  25. return 0;
  26. }

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')

  1. // strings and c-strings
  2. #include <iostream>
  3. #include <cstring>
  4. #include <string>
  5. int main ()
  6. {
  7. std::string str ("Please split this sentence into tokens");
  8. char * cstr = new char [str.length()+1]; //将string转换成字符串数组,末尾有\0
  9. std::strcpy (cstr, str.c_str());
  10. // cstr now contains a c-string copy of str
  11. char * p = std::strtok (cstr," ");
  12. while (p!=0){
  13. std::cout << p << '\n';
  14. p = std::strtok(NULL," ");
  15. }
  16. delete[] cstr;
  17. return 0;
  18. }
  19. Output:
  20. Please
  21. split
  22. this
  23. sentence
  24. into
  25. 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;

  1. // string::copy
  2. #include <iostream>
  3. #include <string>
  4. int main ()
  5. {
  6. char buffer[20];
  7. std::string str ("Test string...");
  8. std::size_t length = str.copy(buffer,6,5);
  9. buffer[length]='\0';
  10. std::cout << "buffer contains: " << buffer << '\n';
  11. return 0;
  12. }
  13. Output:
  14. buffer contains: string

find

Find content in string (public member function )

  1. // string::find
  2. #include <iostream> // std::cout
  3. #include <string> // std::string
  4. int main () {
  5. std::string str ("There are two needles in this haystack with needles.");
  6. std::string str2 ("needle");
  7. // different member versions of find in the same order as above:
  8. std::size_t found = str.find(str2);
  9. if (found!=std::string::npos)
  10. std::cout << "first 'needle' found at: " << found << '\n';
  11. //这个例子 比较特殊,参数found 是第一次查找的结果值。
  12. //而且 第三个参数 6 是指"needles are small"的,前六个字符。
  13. found=str.find("needles are small",found+1,6);
  14. if (found!=std::string::npos)
  15. std::cout << "second 'needle' found at: " << found << '\n';
  16. found=str.find("haystack");
  17. if (found!=std::string::npos)
  18. std::cout << "'haystack' also found at: " << found << '\n';
  19. found=str.find('.');
  20. if (found!=std::string::npos)
  21. std::cout << "Period found at: " << found << '\n';
  22. // let's replace the first needle:
  23. str.replace(str.find(str2),str2.length(),"preposition");
  24. std::cout << str << '\n';
  25. return 0;
  26. }
  27. Notice how parameter pos is used to search for a second instance of the same search string. Output:
  28. first 'needle' found at: 14
  29. second 'needle' found at: 44
  30. 'haystack' also found at: 30
  31. Period found at: 51
  32. 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 )

在字符串中搜索 与 参数中指定的 任意字符匹配的最后一个字符

  1. // string::find_last_of
  2. #include <iostream> // std::cout
  3. #include <string> // std::string
  4. #include <cstddef> // std::size_t
  5. void SplitFilename (const std::string& str)
  6. {
  7. std::cout << "Splitting: " << str << '\n';
  8. std::size_t found = str.find_last_of("/\\");
  9. std::cout << " path: " << str.substr(0,found) << '\n';
  10. std::cout << " file: " << str.substr(found+1) << '\n';
  11. }
  12. int main ()
  13. {
  14. std::string str1 ("/usr/bin/man");
  15. std::string str2 ("c:\\windows\\winhelp.exe");
  16. SplitFilename (str1);
  17. SplitFilename (str2);
  18. return 0;
  19. }
  20. Splitting: /usr/bin/man
  21. path: /usr/bin
  22. file: man
  23. Splitting: c:\windows\winhelp.exe
  24. path: c:\windows
  25. 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.

  1. / string::find_first_not_of
  2. #include <iostream> // std::cout
  3. #include <string> // std::string
  4. #include <cstddef> // std::size_t
  5. int main ()
  6. {
  7. std::string str ("look for non-alphabetic characters...");
  8. //是和"abcdefghijklmnopqrstuvwxyz "中每一个字符比较,不把这个看成字符串
  9. std::size_t found = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");
  10. if (found!=std::string::npos) {
  11. std::cout << "The first non-alphabetic character is " << str[found];
  12. std::cout << " at position " << found << '\n';
  13. }
  14. return 0;
  15. }
  16. The first non-alphabetic character is - at position 12
  17. .

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结尾

  1. // string::substr
  2. #include <iostream>
  3. #include <string>
  4. int main (){
  5. std::string str="We think in generalities, but we live in details.";
  6. // (quoting Alfred N. Whitehead)
  7. std::string str2 = str.substr (3,5); // "think"
  8. std::size_t pos = str.find("live"); // position of "live" in str
  9. std::string str3 = str.substr (pos); // get from "live" to the end
  10. std::cout << str2 << ' ' << str3 << '\n';
  11. return 0;
  12. }
  13. Output:
  14. think live in details.
  15. .

compare

Compare strings (public member function )

  1. // comparing apples with apples
  2. #include <iostream>
  3. #include <string>
  4. int main ()
  5. {
  6. std::string str1 ("green apple");
  7. std::string str2 ("red apple");
  8. if (str1.compare(str2) != 0)
  9. std::cout << str1 << " is not " << str2 << '\n';
  10. // 6是str1的pos , 5 是str1的len.
  11. if (str1.compare(6,5,"apple") == 0)
  12. std::cout << "still, " << str1 << " is an apple\n";
  13. // str2.size()-5是str2的pos , 5 是str2的len.
  14. if (str2.compare(str2.size()-5,5,"apple") == 0)
  15. std::cout << "and " << str2 << " is also an apple\n";
  16. if (str1.compare(6,5,str2,4,5) == 0)
  17. std::cout << "therefore, both are apples\n";
  18. return 0;
  19. }
  20. Output:
  21. green apple is not red apple
  22. still, green apple is an apple
  23. and red apple is also an apple
  24. therefore, both are apples
  25. .

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的,获取一行字符串

  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <string>
  4. #include <string.h>
  5. using namespace std;
  6. int main(){
  7. char data[100];
  8. char tat[50];
  9. char cmd[2];
  10. while(1){
  11. cout << "cin the cmd:";
  12. cin >> cmd;
  13. string str="\n";
  14. getline(cin,str); //将 回车符 作为输入流cin以清除缓存
  15. cout << "cmd is:" << cmd <<endl;
  16. cout << "getline str is:" << str <<endl;
  17. if(strcmp(cmd , "Y")==0){
  18. cout << "Enter your name: ";
  19. cin.get(data, 100);//cin.getline(data,100); //getline输入超范围,程序会出错,get()不会导致程序出错。但是多余的数据在输入缓存中。
  20. cin.clear(); //cin.get()如果没输入,直接Enter,会发生错误
  21. cin.ignore(1024,'\n'); // 清除 在输入缓存中 多余的数据
  22. cout << " : " << data << endl;
  23. }
  24. else if(strcmp(cmd , "N")==0){
  25. break;
  26. }
  27. else {
  28. cout << "again" << endl;
  29. }
  30. }
  31. return 0;
  32. }

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()

  1. char *str1 = "asdfgh";

  2. char str2[] = "asdfgh";

  3. char str3[8] = {'a', 's', 'd'};

  4. char str4[] = "as\0df";

  5. 执行结果是:

  6. sizeof(str1) = 4; strlen(str1) = 6;

  7. sizeof(str2) = 7; strlen(str2) = 6;

  8. sizeof(str3) = 8; strlen(str3) = 3;

  9. 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()

  1. struct ass_header_listnode{ //先定义一个可用的 listnode
  2. char* key;
  3. char* value;
  4. ass_header_listnode *next;
  5. ass_header_listnode(char *str1 , char *str2, ass_header_listnode *nextl = nullptr){ //结构体的构造函数
  6. key = str1;
  7. value = str2;
  8. next = nextl;
  9. }
  10. };
  11. // 添加 listnode
  12. ass_header_listnode *events = new ass_header_listnode((char*)"Text",(char*)"text");
  13. events = new ass_header_listnode((char*)"Effect" , (char*)"Scroll up", events);
  14. events = new ass_header_listnode((char*)"MarginV", (char*)"0", events);
  15. //遍历 查找元素
  16. ass_header_listnode *ptr_temp = events;
  17. ptr_location_flag = events;
  18. while(ptr_temp != nullptr){
  19. if(strcmp(ptr_temp->key , "Effect") == 0){
  20. ptr_location_flag = ptr_temp;
  21. break;
  22. }
  23. cout << "check ptr_temp->key: " << ptr_temp->key << endl;
  24. ptr_temp = ptr_temp->next;
  25. }

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;

数据的插入

  1. //数据的插入
  2. map<int, string> mapStudent;
  3. //第一种:用insert函数插入pair数据
  4. mapStudent.insert(pair<int, string>(1, "student_one"));
  5. //第二种:用insert函数插入value_type数据
  6. mapStudent.insert(map<int, string>::value_type (2, "student_two"));
  7. //第三种:用数组方式插入数据
  8. mapStudent[3] = "student_three";

数据的遍历

  1. map<string , string>::iterator itBegin;

  2. map<string , string>::iterator itEnd;

  3. itBegin = v4_styles.begin();

  4. itEnd = v4_styles.end();

  5. while(itBegin != itEnd){

  6. ret_format = ret_format.append(itBegin->first); //获取map中的 key值

  7. ret_format = ret_format.append(",");

  8. ret_style = ret_style.append(itBegin->second); //获取map中的value值

  9. ret_style = ret_style.append(",");

  10. itBegin++;

  11. }

    反向迭代器

    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函数;

  1. map<string , string> v4_styles;
  2. v4_styles.insert(pair<string , string>("Name" ,"Default"));
  3. map<string , string>::iterator l_it;
  4. l_it = v4_styles.find("Name"); // 这里没有用循环语句
  5. if(l_it != v4_styles.end()){
  6. cout<<"Find it"<<endl;
  7. }
  8. else {
  9. cout<<"ERROR: not find !"<<endl;
  10. }

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函数,它有三个重载了的函数,下面在例子中详细说明它们的用法

  1. #include <map>
  2. #include <string>
  3. #include <iostream>
  4. using namespace std;
  5. int main(){
  6. map<int, string> mapStudent;
  7. mapStudent.insert(pair<int, string>(1, "student_one"));
  8. mapStudent.insert(pair<int, string>(2, "student_two"));
  9. mapStudent.insert(pair<int, string>(3, "student_three"));
  10. //如果你要演示输出效果,请选择以下的一种,你看到的效果会比较好
  11. //如果要删除1,用迭代器删除
  12. map<int, string>::iterator iter;
  13. iter = mapStudent.find(1);
  14. mapStudent.erase(iter);
  15. //如果要删除1,用关键字删除
  16. int n = mapStudent.erase(1);//如果删除了会返回1,否则返回0
  17. //用迭代器,成片的删除
  18. //一下代码把整个map清空
  19. mapStudent.erase( mapStudent.begin(), mapStudent.end() );
  20. //成片删除要注意的是,也是STL的特性,删除区间是一个前闭后开的集合
  21. }
posted @ 2022-12-20 15:40  bruce_lp  阅读(61)  评论(0)    收藏  举报