C++ Primer Plus学习笔记之String类

C++ Primer Plus学习笔记之String类

一,string类的构造

1)string(const char *s)string对象初始化为s指向的传统的C字符串

2)string(int n,char c)创建一个包含n个元素的string对象,其中每个元素都被初始化为字符c

3)string(const string &s)将一个string对象初始化为string对象s,拷贝构造函数

4)string()创建一个默认的string对象,长度为0,默认构造函数

5)string(const char *s,int n)string初始化为s指向的字符串的前n个字符,即使超过了字符串的结尾

6)string(Iterator begin,Iterator end)将string初始化为区间[begin,end)内的字符

二,string类的输入

1)c 风格的字符串

char str[100];

cin>>str;

cin.getline(str,100);

cin.get(str,100);

2)string对象

string s;

cin>>s;

getline(cin,s);

可选参数,用于指定使用哪一个字符来确定输入的边界

cin.getline(str,100,’:’);

getline(cin,s,’:’);

string版本的getline()函数从输入中读取字符,并将其存储到目标string中,直到发生下面三种情况之一:

1),到达文件结尾

2),遇到分界符

3),读取的字符数达到最大允许值(string::npos和可供分配的内存字节数中较小的一个)

三,string类的使用

1),int find(const string&str,int pos)从字符串的pos位置开始,查找子字符串。如果找到,则返回该子字符串

首次出现的位置,否则返回string::npos

2),begin()指向字符串第一个字符的迭代器

3),end()为超尾的迭代器

4),size()字符串中的元素数

5),capacity()给字符串分配的元素数

 例题:

描述
Given two strings A and B, whose alphabet consist only ‘0’ and ‘1’. Your task is only to tell how many times does A appear as a substring of B? For example, the text string B is ‘1001110110’ while the pattern string A is ‘11’, you should output 3, because the pattern A appeared at the posit
输入
The first line consist only one integer N, indicates N cases follows. In each case, there are two lines, the first line gives the string A, length (A) <= 10, and the second line gives the string B, length (B) <= 1000. And it is guaranteed that B is always longer than A.
输出
For each case, output a single line consist a single integer, tells how many times do B appears as a substring of A.
样例输入
3
11
1001110110
101
110010010010001
1010
110100010101011 
样例输出
3
0
3 
AC代码:
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string s1,s2;
	int n;
	cin>>n;
	while(n--)
	{
		cin>>s1>>s2;
		unsigned int m=s2.find(s1,0);
		int num=0;
		while(m!=string::npos)
		{
			num++;
			m=s2.find(s1,m+1);
		}
		cout<<num<<endl;
	}
}        



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值