栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ string 的使用

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ string 的使用

string有很多的优点,一个一个来看

1.首先就是它对字符串可以直接比较

#include
#include
using namespace std;
string s, t;
int main()
{
	cin >> s >> t;
	cout << (s ==t) << endl;
	return 0;
}

输入的两个字符串不等,判断后便输出了0

相比较于c,确实方便了很多,下面做一个对比

#include
#include 
char m[1000], n[1000];
int main()
{
	int i;
	scanf("%d", &i);
	while (i > 0)
	{
		scanf("%d%d", &m, &n);
		printf("%dn", strcmp(m, n));
	}
	return 0;
}

2.然后很方便的一个就是可以将字符串直接连接 

#include
#include
using namespace std;
string s, t;
int main()
{
	cin >> s>>t;
	cout << s+t << endl;
	return 0;
}

再来对比一下c

#include
#include 
char m[100], n[100];
int main()
{
	scanf("%s%s",m,n);
	strcat(m, n);
	puts(m);
	return 0;
}

 

哈哈,感觉确实没上面那个得劲吧 

3.insert(要插入的位置,要插入的字符串)

#include
#include
using namespace std;
string s;
string t;
int main()
{
	cin >> s>>t;
	s.insert(2, t);
	cout < 

 

字符串t就插入了字符串s中的第二个位置 

#include
#include 
char m[100], n[100],l[100];
int a=0;
int main()
{
	scanf("%s%s",m,n);
	for(int i=0;i 

 4.erase(字符串要开始删除的位置,要删除的个数)

#include
#include
using namespace std;
string s;
string t;
int main()
{
	cin >> s;
	s.erase(2,2);
	cout < 

 5.substr(字符串要开始截取的位置,要截取几个数)

#include
#include
using namespace std;
string s;
string t;
int main()
{
	cin >> s;
	cout << s.substr(2, 4) << endl;
	return 0;
}

  5.find(要查找的字符串,从什么位置开始找(不写的话默认从开头开始找))

找不到返回值-1

找到了返回第一次找到的字符串的下标值

#include
#include
using namespace std;
string s;
string t;
int main()
{
	cin >> s>>t;
	cout << s.find(t) << endl;
	return 0;
}

*************

#include
#include
using namespace std;
string s;
int main()
{
	int x = 10;
	s = to_string(x);//整型转字符
	cout << s << endl;
	int t;
	t= stoi(s);//字符转整型
	cout << t << endl;
	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/690965.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号