C Programer  - 讨论区

标题:C++ 语言基础:字符串基本操作

2014年01月18日 星期六 23:45

C-style string对于初学者来说,非常难以理解和正确使用。很多C++语言的教材都尽量避免涉及C-style string,而是直接讲解C++标准库的string数据类型。C++标准库的string非常直观和容易使用,API非常丰富,代码示例如下:

 

#include <iostream>
#include <string>
#include <cstdio>

using namespace std;

int main() {
	string s1;
	string s2("a simple string");
	string s3="another simple string";
	string s4(s3);
	string s5(s3,8,13);
	string s6(8,'a');
	cout << s1 << endl << s2 << endl << s3 << endl;
	cout << s4 << endl << s5 << endl << s6 << endl;
	
	for(auto s : s3 ) {
		cout << s << " ";
	}
	cout << endl;
	cout << "size of s3: " << s3.size() << endl;
	cout << "max size of s3: " << s3.max_size() << endl;
	cout << "capacity of s3: " << s3.capacity() << endl;
	s3.append(".");
	cout << "now capacity of s3:  " << s3.capacity() << endl;
	s3.reserve(100);
	cout << "now capacity of s3:  " << s3.capacity() << endl;
	s3.clear();
	cout << "now capacity of s3:  " << s3.capacity() << endl;
	cout << "s3 is empty? " << s3.empty() << endl;
	s3.shrink_to_fit();
	cout << "now capacity of s3:  " << s3.capacity() << endl;
	s3=s2;
	cout << "first character: " << s3[0] << endl;
	cout << "first character: " << s3.at(0) << endl;
	cout << "first character: " << s3.front() << endl;
	cout << "last character: " << s3.back() << endl;
	s3+=", yeah";
	s3.push_back('.');
	s3.pop_back();
	printf("s3: %s\n",s3.c_str());
	cout << "please input your name:" ;
	getline(cin,s3);
	cout << "Hello, " << s3 << endl;
	auto p=s2.find("simple");
	s2.replace(p,6,"complex");
	cout << s2 << endl;
	s2.erase(p,7);
	cout << s2 << endl;
	
}

参考资料:

http://www.cplusplus.com/reference/string/string/

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2024

    京ICP备05028076号