C++中的string类用法简介_c++ string-程序员宅基地

技术标签: C++  数据结构与算法  String  C/C++编程语言  

本文主要介绍C++中的string类的常见用法。

1. 概述

string是C++标准库的一个重要的部分,主要用于字符串处理。可以使用输入输出流方式直接进行string操作,也可以通过文件等手段进行string操作。同时,C++的算法库对string类也有着很好的支持,并且string类还和c语言的字符串之间有着良好的接口。

2. 常见用法

2.1 string转换为char*

方法一:使用 c_str() 方法,代码(stringsimple.cpp)如下:

#include <string>
#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
    string strOutput = "Hello World";

    cout << "[cout] strOutput is: " << strOutput << endl;

    // string 转换为 char*
    const char* pszOutput = strOutput.c_str();
    
    printf("[printf] strOutput is: %s\n", pszOutput);

    return 0;
}

编译并执行上述代码,结果如下:

上述代码执行结果说明:

  • cout 可直接输出 string 类的对象的内容;
  • 使用 c_str() 方法转换 string 类型到 char* 类型时,需要为char*添加 const 关键字;
  • printf() 函数不能直接打印 string 类的对象的内容,可以通过将 string 转换为 char* 类型,再使用 printf() 函数打印。

2.1.1 data()方法与c_str()方法

data()方法与c_str()方法相似,都返回 const char* 类型。两者区别和联系如下:

  • 在C++98版本中,c_str()返回 const char* 类型,返回的字符串会以空字符(null character)结尾;
  • 在C++98版本中,data()返回 const char* 类型,返回的字符串不以空字符(null character)结尾;
  • 在C++11版本中,c_str()与data()用法相同(Both string::data and string::c_str are synonyms and return the same value.)

2.2 计算string长度、string字符串比较

示例代码如下:

#include <string>
#include <iostream>

#define HELLOSTR "Hello World"

using namespace std;

int main()
{
    string strOutput = "Hello World";

    int nLen = strOutput.length();

    cout << "the length of strOutput is: " << nLen << endl;

    if (0 == strOutput.compare(HELLOSTR))
    {
        cout << "strOutput equal with macro HELLOSTR" << endl;
    }

    return 0;
}

编译并执行上述代码,结果如下:

[root@node1 /opt/liitdar/mydemos/simples]# ./stringsimple2 
the length of strOutput is: 11
strOutput equal with macro HELLOSTR
[root@node1 /opt/liitdar/mydemos/simples]# 

上述代码执行结果说明:

  • string类型可直接使用 length() 方法计算字符串长度,该方法计算结果为字符串的实际长度,如本例中"Hello World"字符串的长度为11;
  • string类型可使用 compare(const string& str) 方法进行字符串比较。

2.3 string对象判空

可使用 empty() 方法对string类型的对象进行判空,如下:

    if (str2.empty())
    {
        cout << "str2 is empty." << endl;
    }

2.4 char*、char[]转换为string

将 char*、char[] 转换为 string 类型时,直接进行赋值操作,将 char*、char[] 的变量赋值给 string 对象即可。

说明:这里所说的“赋值”操作,实际上是将 char*、char[] 定义的字符串的首地址赋值给 string 对象了。

示例代码(stringtochar.cpp)如下:

#include <string>
#include <iostream>

using namespace std;

int main()
{
    const char* pszName = "liitdar";
    char pszCamp[] = "alliance";

    string strName;
    string strCamp;

    strName = pszName;
    strCamp = pszCamp;

    cout << "strName is: " << strName << endl;
    cout << "strCamp is: " << strCamp << endl;

    return 0;
}

编译并执行上述代码,结果如下:

2.5 string类的find方法

使用string类的find方法,在字符串中检索自字符串是否存在。

2.5.1 用法

用法如下:

size_t find (const string& str, size_t pos = 0) const;
size_t find (const char* s, size_t pos = 0) const;
size_t find (const char* s, size_t pos, size_t n) const;
size_t find (char c, size_t pos = 0) const;

2.5.2 返回值

find函数返回值:

The position of the first character of the first match. If no matches were found, the function returns string::npos.

size_t is an unsigned integral type (the same as member type string::size_type).

2.5.3 示例代码

find方法的示例代码(string_find_test1.cpp)如下:

#include <string>
#include <iostream>

using namespace std;

int main()
{
    // 待检索的字符串
    string strOutput = "|0|1|2|";
    // 需要检索的子串
    string strObj = "|1|";

    // 子串位于字符串中的位置
    size_t nLoc = strOutput.find(strObj);
    // 如果检索到子串在字符串中,则打印子串的位置
    if (nLoc != string::npos)
    {
        cout << "nLoc is: " << nLoc << endl;
    }

    return 0;
}

编译并执行上述代码,结果如下:

2.6 string类的insert方法

使用string类的insert方法,向字符串中插入字符(串)。官方的定义如下:

Inserts additional characters into the string right before the character indicated by pos (or p).

2.6.1 用法

string (1) string& insert (size_t pos, const string& str);
substring (2) string& insert (size_t pos, const string& str, size_t subpos, size_t sublen);
c-string (3) string& insert (size_t pos, const char* s);
buffer (4) string& insert (size_t pos, const char* s, size_t n);
fill (5)

string& insert (size_t pos, size_t n, char c);

void insert (iterator p, size_t n, char c);

single character (6) iterator insert (iterator p, char c);
range (7)

template <class InputIterator>

    void insert (iterator p, InputIterator first, InputIterator last);

2.6.2 示例代码

insert方法的示例代码(string_insert_test1.cpp)如下:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string strDemo = "I am";

    strDemo.insert(4, " good.");

    cout << "strDemo is: " << strDemo << endl;

    return 0;
}

编译并执行上述代码,结果如下:

2.7 int类型转为string类的方法

这里介绍两种常见的 int 类型转换为 string 类的方法,示例代码如下:

#include <string>
#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    // 方法1
    int nNum1 = 123;
    stringstream ss;

    ss << nNum1;
    string strTest1 = ss.str();
    cout << "strTest1 is: " << strTest1 << endl;

    /*
    string strTest2;
    strTest2 << ss;     // stringstream 未定义 << 操作符,故此句报错
    cout << "strTest2 is: " << strTest2 << endl;
    */

    string strTest3;
    ss >> strTest3;
    cout << "strTest3 is: " << strTest3 << endl;

    // 方法2
    int nNum2 = 456;
    string strTest4;
    strTest4 = to_string(nNum2);    // C++11 标准
    cout << "strTest4 is: " << strTest4 << endl;

    return 0;
}

编译并执行上述代码,结果如下:

2.7 替换字符串中的空格

替换字符串中的空格,是一种常见的应用场景,下面通过代码示例介绍使用 string 类实现字符串中空格替换的方法。

示例代码如下:

// 面试题:替换空格
// 题目:请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入“We are happy.”,
// 则输出“We%20are%20happy.”。

#include <iostream>
#include <string>

/* length 为字符串str可供使用的最大容量,大于或等于字符串str的实际长度 */
void ReplaceBlank(string & str, const int & length)
{
    if (str == "" && length <= 0)
    {
        return;
    }

    // originalLength为字符串str的实际长度
    int originalLength = 0;
    int numberOfBlank = 0;
    for (int i = 0; str[i] != '\0'; i++)
    {
        ++ originalLength;

        if (str[i] == ' ')
        {
            ++ numberOfBlank;
        }
    }

    // newLength为把空格替换成'%20'之后的长度
    int newLength = originalLength + numberOfBlank * 2;
    if (newLength > length)
    {
        return;
    }

    // 根据空格数量,重新分配str所占空间
    str.resize(newLength);
    
    // 设定原始字符串和更新后字符串的索引值
    int indexOfOriginal = originalLength - 1;
    int indexOfNew = newLength - 1;
    // 由尾至头,依次检索原始字符串内容
    while (indexOfOriginal >= 0 && indexOfNew > indexOfOriginal)
    {
        if (str[indexOfOriginal] == ' ' && numberOfBlank != 0 )
        {
            // 具体的替换位置与原始字符串中空格的数量有关
            // 需根据原始字符串中空格的数量设置偏移量
            str.replace(indexOfOriginal + (numberOfBlank - 1) * 2, 3, "%20");
            
            -- numberOfBlank;
            indexOfNew = indexOfNew - 3;
        }
        else
        {
            str.replace(indexOfNew, 1, 1, str[indexOfOriginal]);
            -- indexOfNew;
        }

        -- indexOfOriginal;
    }
}

// ==================== 测试代码 ====================
void Test(const string & testName, string & str, const int & length, const string & expected)
{
    if (testName != "")
    {
        cout << testName << " begins: " << endl;
    }
    
    if (expected == "" && str == "")
    {
        cout << "passed." << endl;
        return;
    }

    ReplaceBlank(str, length);

    if (expected == "" && str != "")
    {
        cout << "failed." << endl;
    }
    else if (0 == str.compare(expected))
    {
        cout << "passed." << endl;
    }
    else
    {
        cout << "failed." << endl;
    }
}

// 空格在句子中间
void Test1()
{
    const int & length = 100;
    string str = "hello world";
    
    Test("Test1", str, length, "hello%20world");
}

// 空格在句子开头
void Test2()
{
    const int & length = 100;
    string str = " helloworld";
    
    Test("Test2", str, length, "%20helloworld");
}

// 空格在句子末尾
void Test3()
{
    const int & length = 100;
    string str = "helloworld ";
    
    Test("Test3", str, length, "helloworld%20");
}

// 连续有两个空格
void Test4()
{
    const int & length = 100;
    string str = "hello  world";
    
    Test("Test4", str, length, "hello%20%20world");
}

// 传入空字符串
void Test5()
{
    string str = "";
    
    Test("Test5", str, 0, "");
}

//传入内容为一个空格的字符串
void Test6()
{
    const int & length = 100;
    string str = " ";
    
    Test("Test6", str, length, "%20");
}

// 传入的字符串没有空格
void Test7()
{
    const int & length = 100;
    string str = "helloworld";
    
    Test("Test7", str, length, "helloworld");
}

// 传入的字符串全是空格
void Test8()
{
    const int & length = 100;
    string str = "   ";
    
    Test("Test8", str, length, "%20%20%20");
}

int main()
{
    Test1();
    Test2();
    Test3();
    Test4();
    Test5();
    Test6();
    Test7();
    Test8();

    return 0;
}

上述代码的运行结果如下:

2.8 获取string最后一个字符

使用back函数获取字符串最后一个字符,用法如下:

char c = s.back();

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/liitdar/article/details/80498634

智能推荐

linux下编译GDAL外加扩展格式支持(五)--完-程序员宅基地

文章浏览阅读229次。接1、2、3、4篇。10、安装mysql支持安装fedora15或者16系统时若选择安装mysql数据库,则必须自行安装mysql开发包。因为自带默认数据库不会安装这个包。否则会遇到mysql错误:ogr_mysql.h:34:23: fatal error: my_global.h: No such file or directory#问题原因:找不到mysql头文件..._linux gdal netcdf5

Linux tc qdisc 模拟网络丢包延时-程序员宅基地

文章浏览阅读1.2k次。Linux tc qdisc 模拟网络丢包延时_tc qdisc

linux64bit 安装 jdk 1.7-程序员宅基地

文章浏览阅读336次。linux64bit 安装 jdk 1.7下载地址 : https://edelivery.oracle.com/otn-pub/java/jdk/7u21-b11/jdk-7u21-linux-x64.rpm0. 卸载rpm版的jdk: #rpm -qa|grep jdk 显示:jdk-1.6.0_10-fcs 卸载:#rpm -e --nodep..._liunx64位得jdk1.7

【Linux笔记】-----Nginx/LVS/HAProxy负载均衡的优缺点_中间件应用场景nginx lvs proxy-程序员宅基地

文章浏览阅读552次。开始听到负载均衡的时候,我第一反应想到的是链路负载均衡,在此之前主要是在学习网络方面知识,像在NA、NP阶段实验做链路负载均衡时常会遇到,后来还接触到SLB负载分担技术,这都是在链路基础上实现的。 其实负载均衡可以分为硬件实现负载均衡和软件实现负载均衡。 硬件实现负载均衡:常见F5和Array负载均衡器,配套专业维护服务,但是成本昂贵。 软件实现负载均衡:常见开源免费的负载均衡软件有Ngin..._中间件应用场景nginx lvs proxy

多维时序 | MATLAB实现CNN-LSTM多变量时序预测_cnn可以进行多步预测-程序员宅基地

文章浏览阅读4.7k次。多维时序 | MATLAB实现CNN-LSTM多变量时序预测目录多维时序 | MATLAB实现CNN-LSTM多变量多步预测基本介绍模型特点程序设计学习总结参考资料基本介绍本次运行测试环境MATLAB2020b,MATLAB实现CNN-LSTM多变量多步预测。模型特点深度学习使用分布式的分层特征表示方法自动提取数据中的从最低层到最高层固有的抽象特征和隐藏不变结构. 为了充分利用单个模型的优点并提高预测性能, 现已提出了许多组合模型。CNN 是多层前馈神经网络, 已被证明在提取隐藏_cnn可以进行多步预测

随便推点

【9.3】用户和组的管理、密码_polkitd:input 用户和组-程序员宅基地

文章浏览阅读219次。3.1 用户配置文件和密码配置文件3.2 用户组管理3.3 用户管理3.4 usermod命令3.5 用户密码管理3.6 mkpasswd命令_polkitd:input 用户和组

pca算法python代码_三种方法实现PCA算法(Python)-程序员宅基地

文章浏览阅读670次。主成分分析,即Principal Component Analysis(PCA),是多元统计中的重要内容,也广泛应用于机器学习和其它领域。它的主要作用是对高维数据进行降维。PCA把原先的n个特征用数目更少的k个特征取代,新特征是旧特征的线性组合,这些线性组合最大化样本方差,尽量使新的k个特征互不相关。关于PCA的更多介绍,请参考:https://en.wikipedia.org/wiki/Prin..._inprementation python code of pca

内存地址Linux下内存分配与映射之一-程序员宅基地

文章浏览阅读35次。发一下牢骚和主题无关:地址类型:32位的cpu,共4G间空,其中0-3G属于用户间空地址,3G-4G是内核间空地址。用户虚拟地址:用户间空程序的地址物理地址:cpu与内存之间的用使地址总线地址:外围总线和内存之间的用使地址内核逻辑地址:内存的分部或全体射映,大多数情况下,它与物理地址仅差一个偏移量。如Kmalloc分..._linux 内存条与内存地址

自动化测试介绍_自动化测试中baw库指的什么-程序员宅基地

文章浏览阅读1.3k次,点赞2次,收藏16次。什么是自动化测试?   做测试好几年了,真正学习和实践自动化测试一年,自我感觉这一个年中收获许多。一直想动笔写一篇文章分享自动化测试实践中的一些经验。终于决定花点时间来做这件事儿。  首先理清自动化测试的概念,广义上来讲,自动化包括一切通过工具(程序)的方式来代替或辅助手工测试的行为都可以看做自动化,包括性能测试工具(loadrunner、jmeter),或自己所写的一段程序,用于_自动化测试中baw库指的什么

a0图框标题栏尺寸_a0图纸尺寸(a0图纸标题栏尺寸标准国标)-程序员宅基地

文章浏览阅读1.6w次。A0纸指的是一平方米大小的白银比例长方形纸(长为1189mm宽为841mm)。A0=1189mm*841mm A1=841mm*594mm 相当于1/2张A0纸 A2=594mm*420mm 相当于1/4.A1图纸大小尺寸:841mm*594mm 即长为841mm,宽为594mm 过去是以多少"开"(例如8开或16开等)来表示纸张的大小,我国采用国际标准,规定以 A0、A1、A2、.GB/T 14..._a0图纸尺寸

TreeTable的简单实现_treetable canvas-程序员宅基地

文章浏览阅读966次。最终效果图:UI说明:针对table本身进行增强的tree table组件。 tree的数据来源是单元格内a元素的自定义属性:level和type。具体代码如下:Java代码 DepartmentEmployeeIDposi_treetable canvas