string数据结构内部排序,查找和输入输出处理——C++新手上机疑难点总结④

string数据结构内部排序,查找和输入输出处理——C++新手上机疑难点总结④

  • 1. string内部排序:
  • 2. string内查找特定字符或字符串:
  • 3. string的输入输出:

1. string内部排序:

如果有一个字符串的内容为"weferserseg",需要我们按照字典序对其进行排序,最简单的方法是直接使用sort函数:

#include 
#include 
#include 

using namespace std;

int main()
{
     

    string str = "weferserseg";
    cout << "Before:" << str << endl;

    sort(str.begin(), str.end());
    cout << "After: " << str << endl;

    return 0;
}

运行结果为:

Before:weferserseg
After: eeeefgrrssw

Process returned 0 (0x0)   execution time : 0.283 s
Press any key to continue.

2. string内查找特定字符或字符串:

使用find()函数。若找到则返回对应下标,找不到则返回string::npos。

3. string的输入输出:

直接使用string接收输入,默认会在遇到空格时停止输入。
如果想要读取一整行带空格的内容作为string的内容,需要使用getline()函数。

#include 
#include 
#include 

using namespace std;

int main()
{
     

    string str1;
    string str2;

    getline(cin, str1);
    cin >> str2;

    cout << "str1:" << str1 << endl;
    cout << "str2:" << str2 << endl;

    return 0;
}

输入:

qwe rty
qwe rty

输出:

str1:qwe rty
str2:qwe

Process returned 0 (0x0)   execution time : 8.975 s
Press any key to continue.

你可能感兴趣的:(上机小技巧)