1.find
string (1) | size_t find (const string& str, size_t pos = 0) const;//注意这里pos是全缺省参数,可修改。 find('.',3); |
---|---|
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_t n) const; |
character (4) | size_t find (char c, size_t pos = 0) const; |
- 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'
- }
2.c_str
函数返回值:const char* c_str() const; c++为了兼容c,提出c_str,c_string是以斜杠零为结束标志,而string不包括斜杠零。char*a = "sdfsdf";转成string,需要用到c_str string aa = a.c_str();
This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null-character ('\0') at the end.
3.reverse(str.begin(),str.end());
4.string可以使用迭代器,但是一般使用operate[],vector也常用[],
5.to_string(T ) stoi等
6.istream& getline (istream& is, string& str);
练习:输入“i like china.”,输出“china. like i”
- // ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
- #include
- #include
- #include
- using namespace std;
- void reverse(string &str)
- {
- int end = str.size();
- for (int i = 0; i < str.size() / 2; i++)
- {
- swap(str[i], str[end - 1]);
- end--;
- }
- }
- int main()
- {
- string str;
- string newstr;
- getline(cin, str);
- int end = str.size();
- for (int i = 0; i < str.size()/2; i++)
- {
- swap(str[i], str[end - 1]);
- end--;
- }
- cout << str;
-
- size_t pos = str.find(' ');
- while (pos <= end)
- {
- string temp = str.substr(0, pos);
- reverse(temp);
- newstr.append(temp+" ");
- str = str.substr(pos+1);
- pos = str.find(' ');
- if (pos == std::string::npos)
- {
- reverse(str);
- newstr.append(str);
- break;
- }
- }
-
- return 0;
- }
1.算法库中sort函数只适用于内存连续 Vector,可以先把数据拷贝到vector,sort排序,再拷贝回list;
list有单独的sort