zoukankan      html  css  js  c++  java
  • 使用string对象

     1 /*
     2 2020年3月25日14:03:31
     3 对于C++中string对象的学习 
     4 */
     5 
     6 #include<iostream>
     7 #include<string>  //头文件 
     8 using namespace std;
     9 
    10 int main()
    11 {
    12     string word1 = "Game";
    13     string word2("Over");
    14     string word3(3,'!');
    15     string phrase = word1 + " " + word2 + word3;
    16     cout << "This phrase is : " << phrase << endl << endl;
    17     
    18     cout << "The phrase has " << phrase.size() << " characters in it." << endl << endl;
    19     cout << "The character at position 0 is : " << phrase[0] << endl << endl;
    20     cout << "Changing the character at position 0." << endl;
    21     phrase[0] = 'L';
    22     cout << "The phrase is now : " << phrase << endl << endl;
    23     for(unsigned int i = 0; i < phrase.size(); i ++)
    24     {
    25         cout << "Character at position " << i << " is : " << phrase[i] << endl;
    26     }
    27     cout << "
    The sequence 'Over' begain at location ";
    28     cout << phrase.find("Over") << endl;
    29     if(phrase.find("eggplant") == string::npos)
    30     {
    31         cout << "'eggplant' is not in the phrase." << endl << endl;
    32      } 
    33      phrase.erase(4,5);
    34      cout << "The phrase is now : " << phrase << endl;
    35      
    36      phrase.erase(4);
    37      cout << "The phrase id now : " << phrase << endl;
    38      
    39      phrase.erase();
    40      cout << "The phrase is now : " << phrase << endl;
    41      if(phrase.empty())
    42      {
    43          cout << "
    The phrase is no more !" << endl;
    44        }  
    45     return 0;
    46 }

     一、创建string对象

    string word1 = "Game";  —— 使用赋值运算符
    string word2("Over"); 
    string word3(3,'!'); —— 由提供给它的字符组成,且长度等于提供的数。

    二、string对象的连接

    +运算符—— 重载

    三、size()/length()成员函数

    phrase.size()通过成员选择运算符.(点号)调用。

    返回string对象的大小——所包含的字符数,包括空格

    四、索引string对象

    string对象存储一个char型值的序列。

    下标运算符[]和索引号可以访问其中任何一个char型值。

    注意:索引是从0开始的。

    五、使用find()成员函数

    返回值是要搜索的string对象在调用string对象中第一次出现的位置。

    如果要搜索的字符串在调用字符串中不存在:

    返回文件string中定义的一个特殊常量,该常量通过string::npos来访问。

    六、使用erase()成员函数

    从string对象中移除指定子字符串。

    1.指定子字符串的起始位置和长度。

    2.只提供子字符串的起始位置——直到末尾的全部字符都删除

    3.erase()不提供实参——成为空字符串。

    七、使用empty()成员函数

    返回bool型值。

    如果string对象为空,返回true,否则返回false.

  • 相关阅读:
    转载的:关于matlab中princomp的使用说明
    STL容器Vector
    Ubuntu20.04下创建Pycharm桌面图标
    c++和c中const的区别
    内存性能分析\垃圾回收 文章
    jq使用教程
    iOS15适配 UITableView下移22px
    linux 内核头文件(转)
    bjfu1143 小蝌蚪安家 解题报告
    hdu 1874 畅通工程续 flody
  • 原文地址:https://www.cnblogs.com/wlyperfect/p/12566389.html
Copyright © 2011-2022 走看看