C++ 字符串操作

1.1 C++ 字符串操作

2.2字符数组的常用操作

下面几个函数需要额外引入头文件:

#include <string.h>
  1. strlen(str),求字符串的长度
  2. strcmp(a, b),比较两个字符串的大小,a < b返回-1,a == b返回0,a > b返回1。这里的比较方式是字典序!
  3. strcpy(a, b),将字符串b复制给从a开始的字符数组。
#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    char a[100] = "hello world!", b[100];

    cout << strlen(a) << endl;

    strcpy(b, a);

    cout << strcmp(a, b) << endl;

    return 0;
}

2.3遍历字符数组的字符

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
	char a[100] = "what fk";
	int len = strlen(a);
	for (int i = 0; i < len; i++)
		cout << a[i] << endl;

	return 0;
}

3.标准库类型string

<string> 是C++标准库头文件,包含了拟容器class std::string的声明

另外补充

1.<cstring>是C标准库头文件<string.h>的C++标准库版本, 包含了C风格字符串(NUL即’\0’结尾字符串)相关的一些类型和函数的声明,例如strcmp、strchr、strstr等。

2.<castring>和<string.h>的最大区别在于,其中声明的名称都是位于std命名空间中的,而不是后者的全局命名空间。

3.1 定义和初始化

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string a ;
	string b = a;
	if(a == b) cout << "stan";
	return 0;
}

3.2 string的操作

1)读写操作

注意:不能用printf直接输出string,

需要写成:printf(“%s”, s.c_str());

#include <iostream>
#include <string>

using namespace std;

int main()
{
	
	string s1 , s2;
	cin >> s1 >> s2;
	cout << s1 << s2 << endl;
	printf("%s", s1.c_str());

	return 0;
}
2)使用getline读取一整行
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s1;
	getline(cin, s1);
	cout << s << endl;

	return 0;
}
3)string的方法操作

size的使用,得到字符长度

⚠注意size是无符号整数,因此 s.size() <= -1一定成立

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s1 = "abcde";
	int len = s1.size();
	cout << len << endl;

	return 0;
}
4)字符串和string相加
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s1 = "abcde";
	string s2 = s1 + "efg";
	string s3 = "efg" + s1;
    //会报错:gument domain error (DOMAIN)
	// string s4 = "efg" + 123;
    //表达式必须具有整数或未区分范围的枚举类型
	// string s5 = "asdf" +"asd"
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;
	return 0;
}

🚩也就是说每个加法运算的两侧必须至少有一个string

3.3处理string对象中的字符

可以将string对象当成字符数组来处理:

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s1 = "one";
	for(int i= 0;i <s1.size();i++)
		cout << s1[i];


	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

弈鸣coding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值