C++字符串

字符串

  • 定义初始化string对象
string s1;		//默认初始化,s1是一个空字符串
string s2=s1;			//s2是s1的副本
string s3 = "hello";	//s3使该字符串字面值的副本
string s4(10, 'C');		//s4的内容是CCCCCCCCCC 
  • 字符串的大小
//length和size函数
#include<iostream>
#include<string>
using namespace std;
int main() {
	string firstName;
	string fullName;
	firstName = "Alexandra";
	cout << firstName.length() << endl;
	cout << firstName.size() << endl;
	fullName = firstName + "kyle";
	cout << fullName.length() << endl;
	cout << fullName.size() << endl;
	system("pause");
	return 0;
}
  • 定位字符
#include<iostream>
#include<string>
using namespace std;
int main() {
	//find函数
	string str = "I am a goood men";
	cout << str.find("a") << endl;
	*/

	//substr函数
	/*
	string myString, first;
	myString = "programming and problem Solving";
	first = myString.substr(24, 40);
	cout << first << endl;
	*/

	//at函数:访问字符串中的字符,从零开始
	/*
	string myString1, letter;
	myString1 = "programming and problem Solving";
	letter = myString1.at(2);
	cout << letter << endl;
	
	system("pause");
	return 0;
}
  • 转换大小写,需要引入头文件
#include<iostream>
#include<string>
#include<cctype>
using namespace std;
int main() {
	string myString2;
	char ch1, ch2;
	myString2 = "programming and problem Solving";
	ch1 = toupper(myString2.at(0));
	ch2 = towlower(myString2.at(24));
	cout << myString2 << "\n"<< ch1 <<"\n"<< ch2 << endl;
	system("pause");
	return 0;
}

实战“抵押贷款计算器”

#include<iostream>
#include<string>
#include<cmath>		//包含大量数学函数的头文件
using namespace std;
int main() {
	float Debt, Interest_rate;
	int time;
	cout << "欠款:" << endl;
	cin >> Debt;
	cout << "还款时间:" << endl;
	cin >> time;
	cout << "最新利率:" << endl;
	cin >> Interest_rate;
	float month_Interest = Interest_rate / 12;
	int number_of_payments = time*12;
	float payment;
	payment = Debt * pow(1 + month_Interest, number_of_payments) * month_Interest
		/ (pow(1+month_Interest,number_of_payments) - 1);
	cout << "月供金额: " << payment << endl;
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值