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

C++ string

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

C++ string

初始化string 对象的方式

string s1;默认构造函数 s1 为空串
string s2(s1);将 s2 初始化为 s1 的一个副本
string s3(“value”);将 s3 初始化为一个字符串字面值副本
string s4(n, ‘c’);将 s4 初始化为字符 ‘c’ 的 n 个副本
string 对象的读写

• 读取并忽略开头所有的空白字符(如空格,换行符,制表符)。
• 读取字符直至再次遇到空白字符,读取终止。
1、读取一行

int main()
{
string s; // empty string
cin >> s; // read whitespace-separated string into s //输入hello world
cout << s << endl; // write s to the output	//输出hello
return 0;
}

2、可以把多个读操作或多个写操作放在一起

string s1, s2;
cin >> s1 >> s2; // read first input into s1, second into s2     //输入 hello world
cout << s1 << s2 << endl; // write both strings		//输出 helloworld

3、读入未知数目的string 对象
string 的输入操作符也会返回所读的数据流,因此,可以把输入操作作为判断条件

int main()
{
	string word;
	// read until end-of-file, writing each word to a new line
	while (cin >> word)
	cout << word << endl;
	return 0;
}

4、使用getline 读取整行文本
getline 并不忽略行开头的换行符。只要 getline 遇到换行符,即便它是输入的第一个字符,getline 也将停止读入并返回

int main()
{
	string line;
	// read line at time until end-of-file
	while (getline(cin, line))
	cout << line << endl;
	return 0;
}
string 对象的操作
s.empty()如果 s 为空串,则返回 true,否则返回 false。
s.size()返回 s 中字符的个数
s[n]返回 s 中位置为 n 的字符,位置从 0 开始计数
s1 + s2把 s1 和s2 连接成一个新字符串,返回新生成的字符串
s1 = s2把 s1 内容替换为 s2 的副本
v1 == v2比较 v1 与 v2 的内容,相等则返回 true,否则返回 false
!=, <, <=, >, and >=保持这些操作符惯有的含义
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/779227.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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