string中成员函数的相关用法

string中成员函数的相关用法

#include "stdafx.h"
#include <iostream>
using namespace std;
#include <string>


//string 不是关键字 而是一个类

int _tmain(int argc, _TCHAR* argv[])
{
	string s = "china";
	string s2 = "is great";
	s += s2;//string的连接
	cout << s << endl;


	cout <<"s.size()= "<<s.size() << endl; //利用.size()方法求长度大小
	cout << "s.length()= " << s.length() << endl;


	//string的比较
	if (s == s2)
		cout << "s=s2" << endl;
	else if (s > s2)
		cout << "s>s2" << endl;
	else
		cout << "s<s2" << endl;



	//对字符串中下标的操作
	cout << s[3] << endl;
	cout << (s.c_str())[3] << endl;
	s[3] = 'w';
	cout << s << endl;
	cout << s.at(1) << endl; //.at(int) 函数能返回string中下标为int的数据



	//string和char* 类型之间的转换 .c_str()
	char buf[1024];
	strcpy(buf, s.c_str()); 
	//利用.c_str()的方法将string类型返回成char* 类型 赋值给字符数组buf
	cout << "***" << buf << endl;



	//string之间的交换
	string str = "china";
	string str2 = "xxxx";
	cout << str << str2 << endl;

	str.swap(str2); //利用.swap(s)的方法将俩个string交换
	cout << str << str2 << endl;



	//查找字符串中的字符或者字符串 find函数
	//int find(char c,int pos=0);
	//int find(char* s,int pos=0);
	string ss = "china";

	int n = ss.find('i', 0); //也可以查找字符串中的字符串如 find('in',0)
	//表示从这个字符串的0下标开始查找 
	//第一次出现'i'字符的下标 并返回其下标 如果找不到则返回-1
	cout << "n=" << n << endl;



	//stirng 类型数组 (高效、且不会造成空间浪费)
	string sArray[10] = {
		"0",
		"1",
		"22",
		"333",
		"4444",
		"55555",
		"666666",
		"7777777",
		"88888888",
		"999999999",
	};
	for (int i = 0; i<10; i++)
	{
		cout << sArray[i] << endl;
	}

	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值