码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-12-15 15:03:24      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:cin   举例   enter   指针   复制   bool   get   nbsp   ring   

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;
}

 

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

标签:cin   举例   enter   指针   复制   bool   get   nbsp   ring   

原文地址:http://www.cnblogs.com/leosirius/p/8042709.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!