[C++竞赛]:字符串note

Part 1 啥是字符串

将字符串储存在字符数组中,以“\0”结尾。

用字符串为字符数组赋,初值比用字符常数赋值时多占一个字节

Part 2 数组中的字符串
char s[]="c++ program";

定义初始化字符数组

Part 3 关于string的字符串

strcpy()

作用,将字符串2拷贝到字符串1.只复制第一个\0前的内容

strcat()

作用:连接2个字符数组的字符串,将字符串2连接到字符串1的后面,结果放在字符数组1中

strlen()

作用:返回字符串中有效字符的个数,不包括\0 

strcmp()

作用:比较字符数组1和字符数组2,

1.如果字符串相等,返回值==0

2.如果字符串1>字符串2,返回值>1

3.如果字符串1<字符串2,返回值<1

Part 4 string类型

*****string不是关键字!!!

格式:string 变量名;

string变量的初始化(两种):

#include <bits/stdc++.h>
//#include <string> --> string的头文件!

using namespace std;

int main()
{
	string s1="ezsxrdctfvygbhu";
//	cin >> s;
	cout << s1 << endl;
	
	string s2(5,'z');
	cout << s2;
}

万能的string(string的用法):

#include <bits/stdc++.h>
using namespace std;

int main()
{
	string str1 = "I like apple";
	string str2;
	string str3 = "and banana";
	
	//与字符数组相比,无需strcpy
	str2 = str1;
	cout << str2 << endl;
	
	/*
	可以直接通过比较运算符比较
	无需strcmp
	*/
	cout << (str1 == str2) << endl;
	
	//可以直接通过拼接符拼接
	//无需strcat
	str1 = str1 + " very much";
	cout << str1 << endl;
	str2 += str3;
	// 也可以用 str2.append(str3);
	cout << str2;
	
}

string中的函数

1. find函数:

#include <bits/stdc++.h>
using namespace std;

int main()
{
	string s1 = "hello world hello";
	string s2 = "llo";
	string s3 = " ";
	
	cout << s1.find(s2) << endl;       //如果找到了,返回第一次出现的位置
	cout << s1.find(s3) << endl;
	cout << s2.find(s3) << endl;       //如果找不到,返回string::npos
	cout << (int)s2.find(s3) << endl;        // string::npos 换成整型时为 -1
	return 0;
}

2.insert函数:

#include <bits/stdc++.h>
using namespace std;

int main()
{
	string s1 = "hello world";
	string s2 = "ao";
	
	string ans = s1.insert(3,s2);
	cout << ans << endl;
	return 0;
}

3.substr函数

substr:

变量名.substr(位置,长度);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值