复合类型之字符串

字符串基本概念

  1. 字符串是存储在内存的连续字节中的一系列字符,所以意味着可以存储在char数组中
  2. 字符串有两种形式,一种是C风格字符串,另外一种是string类
  3. C风格字符串以空字符结尾, '\0'
  4. char str[3] = {'a', 'b', 'c', '\0'};

字符串常量

  1. 避免像上面那种写法,可以写成字符串常量char str[] = "abc" , 注意是双引号

strlen() 和 sizeof()

  1. strlen() 返回存储在数组中字符串的长度,而不是数组本身的长度;只计算可见的字符,而不将空字符计算在内;标准头文件include <cstring>
  2. sizeof() 返回字符数组长度
int main()
{
    char str[] = "hello world";
    cout << "strlen compute: " << strlen(str) << endl;
    cout << "sizeof compute: " << sizeof(str) << endl;
    return 0;
}

strlen compute: 11
sizeof compute: 12

getline() 和 get()

  1. getline() 丢弃换行符
  2. get() 将换行符保存在输入序列中,如果两次调用,那么第二次调用的时候看到的第一个字符便是换行符,此时,第二次的调用相当于什么都没敲
int main()
{
    char name[20];    //字符的长度不能超过19,因为‘\0’占了一个位置
    char food[20];

    cout << "Enter your name";
    cin.getline(name,20);
    cout << "Enter your favorite food";
    cin.getline(food,20);

    cout << "I will prepare " << food << ", for you ," << name << endl; 
 
    return 0;
}
int main()
{
    char name[20];    //字符的长度不能超过19,因为‘\0’占了一个位置
    char food[20];

    cout << "Enter your name: ";
    cin.get(name,20).get();
    cout << "Enter your favorite food: ";
    cin.get(food,20);

    cout << "I will prepare " << food << ", for you ," << name << endl; 
 
    return 0;
}

==>如果同时cin 出现了换行符保留在队列中的问题,就用.get()解决

string类

  1. 比数组使用起来方便,隐藏了字符串数组性质,能够像处理普通变量一样处理字符串
  2. 需要包含头文件 include <string>
  3. 初始化: string str = {"hello"} , =可以忽略,并且初始化的时候可以给定空的字符串
  4. 可以用+号对字符串进行拼接

strcpy()与strcat()

  1. strcpy() : 将字符串复制到字符串数组中
  2. strcat() : 将字符串附加到字符串数组后面
#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int main()
{
    
    string str1 = {"hello"};
    string str2 = {"world"};

    char str3[10] = {"nihao"};
    char str4[10] = {"shijie"}; 

    // strcpy(str3,str4);   //复制到字符串数组
    strcat(str3,str4);      //拼接到字符串数组

    cout << str1+str2 << endl;
    cout << str3 << endl;

    cout << "Enter your name : " << endl;
    string name;
    getline(cin,name);
    cout << "Enter your age: " << endl;
    string age;
    getline(cin,age);     //与c风格写法输入的不同

    cout << name << " " << "is " << age << " " <<"year old " << endl;

    return 0;
}
 
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值