洛谷第四天

string class in C++

some functions about string class

#include<iostream>
#include<string>
using namespace std;
int main(){
	string s = "xiaohaha";
	string s1 = "_and";
	s += s1;//you can also use "s.append(b)"  to add two strings
	cout<<s.size()<<endl;//equals s.length()
	cout<<s.substr(4,4)<<endl;//s.substr([pos,]len)
	s1 = "boy*";
	cout<<s.insert(0,s1)<<endl;//s.insert(pos,str),return this string
	cout<<s.find("haha")<<endl;//s.find(str[,pos]),return -1 if not exist

//transform string to character array

	char arr[20];
	int len = s.copy(arr,19);
	arr[len] = '\0';
	//strncpy(arr,s.c_str(),10);
	cout<<arr;
	return 0;
}

read a line

when using fgets(arr,sizeof(arr),stdin) or gets(arr) to read a line,if you don’t deal with the \n in the previous line, it is easy to occur some mistake,below is a way you can avoid this situation.

#include<iostream>
#include<cstdio>
using namespace std;
int main(){
	int num;
	char arr[20];
	scanf("%d\n",&num);//not scanf("%d",&num);
	fgets(arr,sizeof(arr),stdin);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值