Part6 数组、指针与字符串 6.13字符串

1 C风格字符串
字符串常量
各字符连续、顺序存放,每个字符占一个字节,以‘\0’ 结尾,相当于一个隐含创建的字符常量数组
首地址可以赋给char常量指针:

  

const char *STRING1 = "program";//不能用指针修改对象

例:

    char str[8] = { 'p', 'r', 'o', 'g', 'r', 'a', 'm', '\0' };
    char str[8] = "program";
    char str[] = "program";

 

 


2 string类
string实际上是对字符数组操作的封装

string类常用的构造函数:

    1 string(); //默认构造函数,建立一个长度为0的串
        string s1;
    2 string(const char *s); //用指针s所指向的字符串常量初始化string对象
        string s2 = “abc”;
    3 string(const string& rhs); //复制构造函数
        string s3 = s2;
//6-23strin类应用举例
#include<string>
#include<iostream>
using namespace std;
inline void test(const char *title, bool value){
    cout << title << " returns " << (value ? "true" : "false") << endl;
}
int main(){
    string s1 = "DEF";
    cout << "s1 is " << s1 << endl;
    string s2;
    cout << "Please enter s2: ";
    cin >> s2;
    cout << "length of s2: " << s2.length() << endl;
    
    test("s1 <= \"ABC\"", s1 <= "ABC");
    test("\"DEF\" <= s1", "DEF" <= s1);
    
    s2 += s1;
    cout << "s2 = s2 + s1: " << s2 << endl;
    cout << "length of s2:" << s2.length() << endl;
    return 0;
}

 

输入整行字符串
getline可以输入整行字符串(要包string头文件),例如:
  getline(cin, s2);
输入字符串时,可以使用其它分隔符作为字符串结束的标志(例如逗号、分号),将分隔符作为getline的第3个参数即可,例如:
  getline(cin, s2, ',');

//6-24getline函数
#include<iostream>
#include<string>
using namespace std;
int main(){
    for(int i = 0; i < 2; i++){
        string city, state;
        getline(cin, city, ',');
        getline(cin, state);
        cout << "City: " << city << " State: " << state << endl;
    }
    return 0;
}

 

posted @ 2017-12-15 13:58  LeoSirius  阅读(123)  评论(0编辑  收藏  举报