C++学习笔记之字符串(基础)

C++学习笔记之字符串

https://www.runoob.com/cplusplus/cpp-strings.html

C++提供两种类型的字符串表示形式

  • C风格字符串
  • C++string类类型

1、C风格字符串

C风格字符串起源于C语言,在C++中得到继续支持
实质:使用null字符('\0')作为结尾的一维字符数组

char greeting1[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << greeting1 << endl;

char greeting2[] = "Hello";    // 其实长度是6,最后是一个'\0'
cout << greeting2 << endl;

在这里插入图片描述
C++在初始化字符串时,自动将'\0'加到末尾

C++也提供了一系列方法专门供这种C风格的字符串进行使用:

strcpy(s1, s2)

复制字符串 s2 到字符串 s1

#include<iostream>
#include<cstring>   // 需要头文件支持
using namespace std;

int main() {
    char s1[10];
    char s2[] = "Hello";
    strcpy(s1, s2);
    cout << s1 << endl;
}

在这里插入图片描述

strcat(s1, s2)

连接字符串 s2 到字符串 s1 的末尾,连接字符串也可以用 +

#include<iostream>
#include<cstring>
using namespace std;

int main() {
    char s1[] = "Hello";
    char s2[] = ", World!";
    cout << strcat(s1, s2) << endl;
}

在这里插入图片描述

strlen(s1)

返回字符串 s1 的长度

#include<iostream>
#include<cstring>
using namespace std;

int main() {
    char s1[] = "Hello";
    cout << strlen(s1) << endl;
}

在这里插入图片描述
注意,字符串长度和字符数组的长度要区分开

strcmp(s1, s2)

如果 s1 和 s2 是相同的,则返回 0;如果 s1<s2 则返回值小于 0;如果 s1>s2 则返回值大于 0
两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇'\0'为止

#include<iostream>
#include<cstring>
using namespace std;

int main() {
    char s1[] = "Hello";
    char s2[] = "World";
    cout << strcmp(s1, s2) << endl;   // s1<s2 -1
    cout << strcmp(s2, s1) << endl;   // s2>s1  1
    cout << strcmp(s1, "Hello") << endl;   // 相等 0
}

在这里插入图片描述

strchr(s1, ch)

返回一个指针,指向字符串 s1 中字符 ch 的第一次出现的位置

#include<iostream>
#include<cstring>
using namespace std;

int main() {
    char s1[] = "Hello";
    char ch = 'l';
    char* p = strchr(s1, ch);
    cout << p << endl;
}

在这里插入图片描述

strstr(s1, s2)

返回一个指针,指向字符串 s1 中字符串 s2 的第一次出现的位置

#include<iostream>
#include<cstring>
using namespace std;

int main() {
    char s1[] = "Hello";
    char s2[] = "el";
    char* p = strstr(s1, s2);
    cout << p << endl;
}

在这里插入图片描述

2、C++string类类型

C++ 标准库提供了 string 类类型,支持C风格字符串的所有的操作,另外还增加了其他更多的功能

#include<iostream>
using namespace std;

int main() {
    string s1 = "Hello";
    string s2 = ", World";
    cout << s1 + s2 << endl;  // 拼接 Hello, World
}
#include<iostream>
using namespace std;

int main() {
    string s1 = "Hello";
    cout << s1.size() << endl;   // 长度 5
}
#include<iostream>
using namespace std;

int main() {
    string s1 = "Hello";
    string s2 = "Hey";
    s1 = s2;     // 赋值替换 Hey
    cout << s1 << endl;
}
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值