C++ string

本文介绍了C++中的string类,包括如何初始化,其特性描述,以及如何使用迭代器进行操作。通过学习,读者将更好地理解和掌握C++中的字符串处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 头文件 。
    #include < string >

  • string类是一个模板类,位于名字空间std中;
    using namespace std;

1. 初始化;

string str;  //空字符串
string str1 = "qazwsx";
string str2 = str1;
string str3("qazwsx");
string str4 (5, 'a');
string str5 (str1,2,3);  //从str1的第2个位置的字符开始,连续3个字符赋值给s5,即s5="zws";
string str6(str1,2); //从str1的2位置的字符开始,将后续的所有字符赋值给str6,即s6="zwsx"; 
string str;
cin>>str;  //当使用C++的cin读入字符串时,程序遇到空白字符就停止读取了。
		   //若输入为“ hello world” ,则 str == "hello";
//如果我们想读取一整行输入,包括空格及空格后面的字符,我们可以使用getline。
string str;
getline(cin, str);
cout << str << endl;   //若输入同样为“hello world”,则str =="hello world";

2.string特性描述

//find, 查找字符串A是否包含子串B
if( strA.find(strB) != string:npos)
	.......//找到了
else
    .......//没找到
   
str.size() ; 		//返回字符串有效字符长度
str.length();		//返回字符串有效的长度
str.capacity() ;	//返回空间总大小,既容量
str.empty() ;		//判断字符串是否为空串,是返回true,不是返回false
void clear(); 		//清空有效的字符

3.迭代器iterator

string::iterator it;
for (it = s1.begin(); it != s1.end(); it++){
    cout << *it << endl;
}

#include<iostream>
#include<string>
#include <algorithm>
using namespace std;

int main(){
//初始化
string a = "apple";
string aa("banana");
cout << "a = " << a << "; sizeof a = "<<a.size()<<endl;
cout << "aa = " << aa << "; sizeof aa = " << aa.size() << endl;

//字符串扩展
string aaa = a + " " + aa;
cout << "aaa= " << aaa<< "; sizeof aaa = " << aaa.size() << endl;
aaa.append(" orange");
cout << "aaa= " << aaa << "; sizeof aaa = " << aaa.size() << endl;

//find()
if (aaa.find("banana") != string::npos) {
	cout << "there is a banana in aaa"<<endl;
}
//迭代器
string::iterator it;
for (it = a.begin(); it != a.end(); ++it) {
	cout << *it ;
}
cout << endl;

//大小写转化
//使用迭代器+toupper
for (it = a.begin(); it != a.end(); ++it) {
	char upper = toupper(*it);
	cout << upper;
}
cout << endl;
//使用transform+toupper(需包含头文件 algorithm)
transform(a.begin(), a.end(), a.begin(), toupper);
cout << "transform+toupper: "<<a << endl;

//string 和 char[ ],char * 相互转换
const char* change ="i need to change char* to string";
string change_to_string = change;
cout << change_to_string << endl;

system("pause");
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值