【C++】C++标准模板库STL (一) string类的使用详解(3)

简介: 【C++】C++标准模板库STL (一) string类的使用详解(2)

6.string类对象的一些其他操作

#include<iostream>
#include<string>
using namespace std;
int main()
{
  string s1("hello world");
  const char* str1 = s1.c_str();
  cout << str1 << endl;
  return 0;
}

#include<iostream>
#include<string>
using namespace std;
int main()
{
  string s1("hello world");
  /*const char* str1 = s1.c_str();
  cout << str1 << endl;*/
  char ch = 'a';
  char* str1 = &ch;
  s1.copy(str1, 3, 2); // 注意此函数不会拷贝完后追加字符串,打印字符串时要小心越界。
  return 0;
}

#include<iostream>
#include<string>
using namespace std;
int main()
{
  //buffer (3)  
  string s1("hello world");
  const char* str = "world";
  int index = s1.find(str, 0, 3);
  cout << index << endl;
  return 0;
}

#include<iostream>
#include<string>
using namespace std;
int main()
{
  //c-string (2)  
  string s1("hello world");
  const char* str = "world";
  int index = s1.rfind(str);
  cout << index << endl;
  return 0;
}

#include<iostream>
#include<string>
using namespace std;
int main()
{
  string s1("hello world");
  int index = s1.find_first_of("wor");
  cout << index << endl;
  return 0;
}

#include<iostream>
#include<string>
using namespace std;
int main()
{
  string s1("hello world");
  string s2 = s1.substr(2, 3);
  cout << s2 << endl;
  return 0;
}

#include<iostream>
#include<string>
using namespace std;
int main()
{
  //string (1)  
  string s1("hello world");
  string s2("iello");
  cout << s1.compare(s2) << endl;
  return 0;
}


7.getline函数

getline的作用是读取一整行,直到遇到换行符才停止读取,期间能读取像空格、Tab等的空白符。

getline函数和cin一样,也会返回它的流参数,也就是cin,所以可以用getline循环读取带空格的字符串。

注意: getline 是非成员函数!

#include<iostream>
#include<string>
using namespace std;
int main()
{
  string s1;
  //这里我们输入"hello world!"
  getline(cin, s1);
  cout << s1 << endl;
  return 0;
}

四、结语

本章的内容都不是很难,但是琐碎的函数与细节特别多,想要掌握好它们还需要多加练习。多去使用它们,相信你会越用越熟悉的。

相关文章
|
1月前
|
编译器 C++
【C++】——初识模板
【C++】——初识模板
32 1
【C++】——初识模板
|
13天前
|
存储 计算机视觉 C++
在C++中实现Armadillo库与OpenCV库之间的数据格式转换
在C++中实现Armadillo库与OpenCV库之间的数据格式转换是一项常见且实用的技能。上述步骤提供了一种标准的方法来进行这种转换,可以帮助开发者在两个库之间高效地转移和处理数据。虽然转换过程相对直接,但开发者应留意数据类型匹配和性能优化等关键细节。
24 11
|
14天前
|
存储 计算机视觉 C++
在C++中实现Armadillo库与OpenCV库之间的数据格式转换
在C++中实现Armadillo库与OpenCV库之间的数据格式转换是一项常见且实用的技能。上述步骤提供了一种标准的方法来进行这种转换,可以帮助开发者在两个库之间高效地转移和处理数据。虽然转换过程相对直接,但开发者应留意数据类型匹配和性能优化等关键细节。
15 3
|
25天前
|
C++
fedora安装静态c和c++库
fedora安装静态c和c++库
|
1月前
|
算法 数据可视化 机器人
Pinocchio - 开源多刚体动力学 C++、Python库
Pinocchio - 开源多刚体动力学 C++、Python库
54 2
|
27天前
|
C++
C/C++静态链接pthread库的坑【-static -pthread】
C/C++静态链接pthread库的坑【-static -pthread】
|
1月前
|
C++
C++标准库探索
C++标准库探索
33 0
|
1月前
|
并行计算 测试技术 开发工具
【简历模板】c/c++软件工程师
【简历模板】c/c++软件工程师
45 0
|
1月前
|
存储 算法 程序员
【STL】string
【STL】string
|
10天前
|
编译器 C++
C++ 类构造函数初始化列表
构造函数初始化列表以一个冒号开始,接着是以逗号分隔的数据成员列表,每个数据成员后面跟一个放在括号中的初始化式。
56 30