关于C++的String用法(新手向)
2013-08-05 08:42
477 查看
最近在接受c++入行向培训,因为本人之前学过一点c#,知道c#的string类型非常好用。但开始学c++发现string居然不是c++的基本类型,不科学啊!正好老师留个作业,要求整理c++的string类用法,于是就研究了一下。
1.string常见的定义与初始化方法
2.string对象的读写
3.string对象的操作
4.string对象的常用方法
1.string常见的定义与初始化方法
//本文所有示例默认都需要引入<string>头文件,下同。 #include <string>
//string的默认构造函数,定义的s1为空。 string s1; //建立一个变量名为s2的字符串,内容与s1相同。 string s2(s1); //建立一个变量名为s3的字符串,内容为“string”。 string s3("string"); //建立一个变量名为s4的字符串,内容为20个'-'(不包括单引号)。 string s4(20,'-');
2.string对象的读写
string s; //需要<iostream>头文件的支持。 std::cin >> s; std::cout << s <<endl;
3.string对象的操作
//如果s字符串为空,则返回true,否则返回false, //并将结果存入变量isEmpty。 bool isEmpty=s.empty(); //返回s字符串中的字符个数,并将结果存入变量i。 //注意:这里的s.size()值并不是int型,但可以直接隐式转换为int。 int i=s.size(); //显示s字串中第Count个字符(位置从0开始)。 int Count; cin >> Count; cout << s[Count] << endl; //将s1与s2连接为一个新的字符串并存入s3。 s3=s1+s2; //比较变量s1与s2的内容,相等返回true,否则返回false, //并将结果存入变量isSame; bool isSame=(s1==s2); //清除s内的所有内容。 s.clear;
4.string对象的常用方法
#include "stdafx.h" #include <iostream> #include <string> using namespace std; int main() { //变量初始化。 string String1 = "HelloWorld!ILoveCpp!"; string String2 = "CodingChangeTheWorld!"; //assign,将字符串String1的第5个字符开始的6个字符存入String1。 //此部分代码运行结果为“World!”。 String1.assign(String1,5,6); cout << String1 <<endl; //将字符串String2的第6个字符开始的6个字符存入String1。 //此部分代码运行结果为“Change”。 String1.assign(String2,6,6); cout << String1 << endl << endl; String1 = "HelloWorld!ILoveCpp!"; String2 = "CodingChangeTheWorld!"; //将字符串String2连接到String1的末尾,并存入String1。 //此部分代码运行结果为“HelloWorld!ILoveCpp!CodingChangeTheWorld!”。 String1.append(String2); cout << String1 << endl; //将字符串String2的第6个字符开始的6个字符连接到String1的末尾。 //此部分代码运行结果为“HelloWorld!ILoveCpp!CodingChangeTheWorld!Change”。 String1.append(String2,6,6); cout << String1 << endl << endl; String1 = "HelloWorld!ILoveCpp!"; String2 = "CodingChangeTheWorld!"; //返回”Change“在String2字符中的位置(注意:从0开始)。 //此部分代码运行结果为“6”. cout << String2.find("Change") << endl << endl; String1 = "HelloWorld!ILoveCpp!"; String2 = "CodingChangeTheWorld!"; //将String2插入String1的第11个字符后。 //此部分代码运行结果为“HelloWorld!CodingChangeTheWorld!ILoveCpp!”。 String1.insert(11,String2); cout << String1 << endl << endl; //返回String1的长度(注意:从0开始)。 //此部分代码运行结果为“41”。 cout << String1.length() << endl << endl; system("pause"); return 0; }
相关文章推荐
- 关于C++的String用法(新手向)
- C++关于string的一些用法
- C++新手上路第七天 string的一些函数用法
- 关于C++中STL的erase用法
- c++中的string常用函数用法总结
- 关于pragma pack的用法--------------C++中的内存对齐问题
- C++ 关于new和delete的一些简单用法
- lua中关于string标准库的用法一
- 新手上路_vc多线程例子,关于AfxBeginThread的用法
- 【新手向】C++中const的用法总结,超级简单的,看不懂的话………………………………………………我再给你讲一遍
- C++ string append方法的常用用法
- C++中关于strtok()函数的用法
- C++_STL之string用法
- C++中string的用法
- C++ STL中string用法
- c/c++:关于typedef的用法总结
- C++中关于string的一些函数的问题
- C++模版STL中 map 和 string, vector 的用法详解!
- C++中关于static关键字的用法
- 关于C和C++中的基本数据类型int、long、long long、float、double、char、string的大小及表示范围