C++ string 详解

string 其实相当于一个保存字符的序列容器,因此除了有字符串的一些常用操作以外,还有包含了所有的序列容器的操作。

1.1 充分使用string 操作符

string 重载了许多操作符,包括 +, +=, <, =, , [], <<, >>等,正式这些操作符,对字符串操作非常方便。

#include <string>
#include <iostream>
using namespace std;
int main()
{
	string strinfo="Please input your name:";
	cout << strinfo ;
	cin >> strinfo;
	if( strinfo == "winter" )
		cout << "you are winter!"<<endl;
	else if( strinfo != "wende" )
		cout << "you are not wende!"<<endl;
	else if( strinfo < "winter")
		cout << "your name should be ahead of winter"<<endl;
	else
		cout << "your name should be after of winter"<<endl;
	strinfo += " , Welcome to China!";
	cout << strinfo<<endl;
	cout <<"Your name is :"<<endl;
	string strtmp = "How are you? " + strinfo;
	for(int i = 0 ; i < strtmp.size(); i ++)
		cout<<strtmp[i];
	return 0;
}

 下面是程序的输出

 

Please input your name:Hero
you are not wende!
Hero , Welcome to China!
How are you? Hero , Welcome to China!

 有了这些操作符,在STL中仿函数都可以直接使用string作为参数,例如 less, great, equal_to 等,因此在把string作为参数传递的时候,它的使用和int 或者float等已经没有什么区别了。

 有了 operator + 以后,你可以直接连加,例如:

string strinfo="Winter";
string strlast="Hello " + strinfo + "!";
string strtest="Hello " + strinfo + " Welcome" + " to China" + " !";//你还可以这样:

 只要你的等式里面有一个 string 对象,你就可以一直连续”+”,但有一点需要保证的是,在开始的两项中,必须有一项是 string 对象。其原理很简单:

系统遇到”+”号,发现有一项是string 对象。
系统把另一项转化为一个临时 string 对象。
执行 operator + 操作,返回新的临时string 对象。
如果又发现”+”号,继续第一步操作。

由于这个等式是由左到右开始检测执行,如果开始两项都是const char* ,程序自己并没有定义两个const char* 的加法,编译的时候肯定就有问题了。

有了操作符以后,assign(), append(), compare(), at()等函数,除非有一些特殊的需求时,一般是用不上。当然at()函数还有一个功能,那就是检查下标是否合法.

如果你希望效率高,还是使用[]来访问,如果你希望稳定性好,最好使用at()来访问。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 C++ 中,string 是一个类,可以用来存储和操作字符串。使用 string 类型需要包含头文件 <string>。 string 类型的特点如下: 1. 可以动态改变字符串的长度。 2. 支持下标访问、迭代器操作和常用的字符串操作函数(如 find、substr 等)。 3. 可以与 C 语言的字符串(即以 '\0' 结尾的字符数组)进行互相转换。 下面是一些常用的 string 类型操作: 1. 初始化字符串: ```cpp string str1 = "hello"; // 直接用字符串初始化 string str2("world"); // 用字符数组初始化 string str3(5, 'a'); // 用字符和长度初始化 ``` 2. 获取字符串长度: ```cpp int len = str.length(); // 获取字符串长度 ``` 3. 字符串拼接: ```cpp string str4 = str1 + str2; // 直接使用加号拼接字符串 str1 += str2; // 使用加等于号拼接字符串 ``` 4. 字符串查找: ```cpp int pos = str.find("world"); // 查找子串,返回第一次出现的位置 ``` 5. 字符串截取: ```cpp string substr = str.substr(pos, len); // 截取子串,从 pos 开始,长度为 len ``` 6. 字符串转换为字符数组: ```cpp const char* cstr = str.c_str(); // 获取指向字符数组的指针 ``` 7. 字符数组转换为字符串: ```cpp string str5 = "hello"; const char* cstr2 = "world"; string str6 = str5 + cstr2; // 直接使用加号拼接字符串和字符数组 string str7(cstr2); // 使用字符数组初始化 ``` 以上是 string 类型的一些常用操作,具体用法还需要根据实际情况进行调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值