关于C++的String用法(新手向)

最近在接受c++入行向培训,因为本人之前学过一点c#,知道c#的string类型非常好用。但开始学c++发现string居然不是c++的基本类型,不科学啊!正好老师留个作业,要求整理c++的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;
}
复制代码

 

原文地址:https://www.cnblogs.com/hzcya1995/p/13318868.html