关于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;
}

参考文献:

《C++Primer中文第四版》人民邮电出版社

《C++ Gossip: 使用 string 型態》 http://openhome.cc/Gossip/CppGossip/string2.html
原文链接: https://www.cnblogs.com/cjlaaa/p/3236727.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/98507

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月10日 上午4:45
下一篇 2023年2月10日 上午4:47

相关推荐