C++学习笔记(Day10 字符串 string类)

本文详细介绍了C++中的string类,包括其构造函数,如使用常量指针初始化和复制构造。重点讲解了如何利用内联函数test进行字符串比较,并演示了使用getline获取整行输入。通过实例展示了字符串连接、比较运算符和连接运算符的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:

constr char *title 是把test中"s1 <= \"ABC"\"的地址作为参数传给title?

字符串常量

  • 例:“program”
  • 各字符连续、顺序存放、每个字符占一个字节,以‘\0’结尾,相当于一个隐含创建的字符常量数组
  • “program”出现在表达式中,表示这一char数组的首地址
  • 首地址可以赋给char常量指针
    const char *STRING1 = "program";

用字符数组存储字符串(C风格字符串)

string类

  • 使用字符串类string表示字符串
  • string实际上是对字符数组操作的封装

string类常用的构造函数

  • string(); //默认构造函数,建立一个长度为0的串                                  例: string s1;
  • string(const char *s); //用指针s所指向的字符串常量初始化string对象 例: string s2 = “abc”;
  • string(const string& rhs); //复制构造函数                                             例: string s3 = s2;
//例 6-23 string 类应用举例
#include <string>
#include <iostream>
using namespace std;
//根据value的值输出true或false
//title为提示文字
inline void test(const char *title, bool value)//inline把函数指定为内联函数.解决一些频繁调用的函数大量消耗栈空间(栈内存)的问题
{
    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;
}

考虑:如何输入整行字符串?

  • 用cin的>>操作符输入字符串,会以空格作为分隔符,空格后的内容会在下一回输入时被读取

输入整行字符串

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

#include <string>
#include <iostream>
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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值