当前位置: 首页 > article >正文

蓝桥杯之c++入门(六)【string】

目录

  • 前言
    • 1. string 概念
    • 2.string 常见操作
      • 2.1 创建字符串
      • 2.2 string字符串的输入
        • 2.2.1 cin的方式
        • 2.2.2 getline 的方式
          • 1. **第一种**
          • 2. **第二种**
      • 2.3 size()
      • 2.4 迭代器(iterator)
        • 2.4.1 begin() 和 end()
      • 2.5 push_back()
      • 2.6字符串的 += 和 + 运算
      • 2.7 pop_back()
      • 2.8 insert ( )
      • 2.9 find()
      • 2.10 substr()
      • 2.11 string的关系运算
        • 2.11.1 支持的关系运算
        • 2.11.2 代码举例1:
        • 2.11.3 代码举例2:
      • 2.12 和string相关的函数
        • 2.12.1 stoi/stol
        • 2.12.2 stod/stof
        • 2.12.3 to_string
  • 总结


前言

前面介绍了通过字符数组保存字符串,然后对字符数组中的字符串做各种操作;
char str[20] = “hello world”;
为了更加简单方便,在 C + + \mathsf{C}\substack{++} C++ 中,又增加了 string 来处理字符串。


正文开始

1. string 概念

string 字符串其实是一种更加高级的封装,String 字符串中包含大量的方法,这些方法使得字符串的操作变得更加简单。string 使用的好,慢慢你就不想使用字符数组来存放字符串了。

那到底什么是string呢?

C + + \mathsf{C}\mathsf{+}\mathsf{+} C++ 中将字符串直接作为一种类型,也就是 string 类型,使用 string 类型创建的对象就是 C + + \mathsf{C}\substack{++} C++ 的字符串。

1 string sl;
2 string $$2$ “abc”;

使用 C + + \mathsf{C}\substack{++} C++ 中提供的 string 时,必须添加头文件

2.string 常见操作

string 文档: https://legacy.cplusplus.com/reference/string/string

2.1 创建字符串

方式解释
string sl创建空字符串
string s2 = "hello world"创建字符串 (常用)
#include <iostream>
#include <string>
using namespace std;

int main()
{
 	string s1;
 	string s2 = "hello world";
 	cout << "s1:" << s1 << endl; //s1:
 	cout << "s2:" << s2 << endl; //s2:hello world
 return 0;
}

创建字符串的方式与前面学习到创建内置数据类型的方式相同,只是这里的字符串类型为string。

1.string sl 表示创建空字符串,相当于创建整型int a,但未给 a 一个初始值。

  1. String s2 = = = “helloworld"表示创建一个字符串s2,它的内容是"helloworld”,要注意S2中的字符串不再以\作为结束标志了。(C语言中的字符串是以\0作为结束标志的)。

在这里插入图片描述

小提示:

上面这个图,仅仅是字符串s2的示意图,实际上 string 类型的字符串比这个要复杂的多,更多的知识得学习 C + + \mathsf{C}\mathsf{+}\mathsf{+} C++ 的类和对象的知识才能明白。

除了以上创建字符串的写法外, C + + \mathsf{C}\substack{++} C++ 中还有一些其他的创建字符串方式。如:

string s("hello world"); //等同于string s1 = "hello world";
string s1 = s; //用一个现成的字符串s,初始化另外一个字符串s1

当然 C + + \mathsf{C}\mathsf{+}\mathsf{+} C++ 中的 string 创建的字符串和 char 类型的数组所表示的字符串还有一个区别,string类型的字符串对象可以直接赋值,比如:

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

2.2 string字符串的输入

2.2.1 cin的方式

可以直接使用cin给 string 类型的字符串中输入一个字符串的数据。

#include <iostream>
#include <string>
using namespace std;
int main()
{
 	string s;
 	//输入 
 	cin >> s;
 	//输出
 cout << s << endl;
 
 return 0;
}
  1. 输入不带空格的字符串:

在这里插入图片描述

  1. 输入带空格的字符串:

在这里插入图片描述

这里我们可以发现,其实cin 的方式给 string类型的字符串中输入数据的时候,可以输入不带空格的字符串。但是如果带有空格,遇到空格也就读取结束了,没有办法正常读取,那怎么办呢?解决办法就是使用getline

2.2.2 getline 的方式

getline是 C + + \mathsf{C}\mathsf{+}\mathsf{+} C++ 标准库中的一个函数,用于从输入流中读取一行文本,并将其存储为字符串。

getline 函数有两种不同的形式,分别对应着字符串的结束方式。

istream& getline (istream& is, string& str);
istream& getline (istream& is, string& str, char delim);

小提示:

  • istream 是输⼊流类型, cin 是 istream 类型的标准输⼊流对象。
  • ostream 是输出流类型, cout 是 ostream 类型的标准输出流对象。
  • getline 函数是输⼊流中读取⼀⾏⽂本信息,所有如果是在标准输⼊流(键盘)中读取数据,就可以传 cin 给第⼀个参数。
1. 第一种

getline 函数以换行符('\n')作为字符串的结束标志,它的一般格式是:

getline(cin, string str)
//cin -- 表⽰从输⼊流中读取信息
//str 是存放读取到的信息的字符串

这种形式的 getline 函数从输入流(例如cin)中读取文本,直到遇到换行符( ‘\n’)为止,然后将读取到的文本(不包括换行符)存储到指定的string 类型的变量 str 中。

#include<iostream>
#include <string>
using namespace std;
int main()
{
	string name;
	getline(cin,name);
	cout << name << endl;
	return 0;
 } 

运行结果如下:

在这里插入图片描述

2. 第二种

getline 函数允许用户自定义结束标志,它的一般格式是:

getline(cin, string str, char delim)
//cin -- 表⽰从输⼊流中读取信息
//str 是存放读取到的信息的字符串
//delim 是⾃定义的结束标志

这种形式的getline 函数从输入流中读取文本,直到遇到用户指定的结束标志字符(delim)为止,然后将读取到的文本(不包括结束标志字符)存储到指定的string 类型的变量str 中。

#include<iostream>
#include <string>
using namespace std;
int main ()
{
 	string name;
 	getline (cin, name, 'q');
 	cout << name << endl;
 
 	return 0;
}

运行结果如下:

在这里插入图片描述
·

小提示:

在使用 C + + \mathsf{C}\substack{++} C++ 中的 string 字符串时,想要输入的字符串中包含空格,那么 getline 函数就是必须的。

在竞赛中为了方便处理字符串,通常会使用 string 类型的字符串,所以在字符串输入的时候getline就很常见,建议认真学习。

2.3 size()

string 中提供了size() 函数用于获取字符串长度

C + + \mathsf{C}\mathsf{+}\mathsf{+} C++ 中关于字符串的操作函数都是包含在 string 中的,所以需要调用这些函数时,通常用’·'点运算符

使用示例:

#include <iostream>
#include <string>
using namespace std;
int main()
{
	string s;
 	string s1 = "hello";
 	string s2 = "hello world";
 	string s3 = "12ab!~        ";
 	
 	cout << s.size() << endl;
 	cout << s1.size() << endl;
 	cout << s2.size() << endl;
 	cout << s3.size() << endl;
	return 0;
 } 

运行结果:
在这里插入图片描述

小提示:

前面我们学到的像char、int、double 等内置类型的数据在操作的时候,不会使用·操作符的。

String是 C + + \mathsf{C}\mathsf{+}\mathsf{+} C++ 提供的一种更加复杂的封装类型,在string 类型的变量中加入了操作这个字符串的各种方法(函数),比如求字符串长度、字符串末尾插入一个字符等操作所以要对string 类型的变量进行各种操作,就可以使用·操作符来使用这些函数。我们可以看下面的例子,大家要仔细体会。

通过 size()能获得字符串的长度,顺便就可以使用这个长度遍历字符串的,注意string 类型的字符串是可以通过下标访问的,比如:

#incldue <iostream>
#include <string>
using namespace std;
int main()
{
 	string s = "abcdef";
 	int i = 0;
 	for(i = 0; i < s.size(); i++)
 	{
 		cout << s[i] << " ";
 	}
 	return 0;
}

2.4 迭代器(iterator)

迭代器是一种对象,它可以用来遍历容器(比如我们现在学习的string)中的元素,迭代器的作用类似于指针,或者数组下标。

不过访问迭代器指向的值,需要解引用(*)。

C + + \mathsf{C}\substack{++} C++ 中的string 提供了多种迭代器,用于遍历和操作字符串中的内容。这里给大家介绍一种最常用的选代器。

2.4.1 begin() 和 end()
  • begin():返回指向字符串第一个字符的迭代器,需要一个迭代器的变量来接收。

  • end():返回指向字符串最后一个字符的下一个位置的迭代器(该位置不属于字符串)。

string 中 begin()和end()返回的迭代器的类型是 string::iterator

 string S = "abcdef"; 
#include <iostream>
using namespace std;
#include <string>
int main()
{
	string s = "abcdef";
	string::iterator it1 = s.begin();
	string::iterator it2 = s.end();
	cout << *it1 << endl;
	cout << *(it2-1) << endl;
	return 0;
 } 

小提示:

迭代器是可以进行大小比较,也可以进行 + 或者-整数运算的。

比如: it++,就是让迭代器前进一步,it--就是让迭代器退后一步。

同一个容器的两个迭代器也可以相减,相减结果的绝对值,是两个迭代器中间元素的个数。

#include <iostream>
#include <string>
using namespace std;
int main()
{
 	string s = "abcdef";
 	string::iterator it1 = s.begin();
 	string::iterator it2 = s.end();
 	cout << (it1 < it2) << endl;
	cout << it1 - it2 << endl;
 	return 0;
}

在这里插入图片描述

正序遍历:

迭代器通常用于遍历字符串的,可以正序遍历,也可以逆序遍历。

int main()
{
	string s = "abcdef"; 
	//auto it 是让编译器?动推到it的类型
	for(auto it = s.begin() ; it < s.end() ; it++)
	{
		cout << *it << " ";
	}
	
	cout << endl;
	//string::iterator 是正向迭代器类型
 	//string::iterator it,是直接创建迭代器,it是针对字符串的迭代器
	for(string::iterator it = s.begin() ; it < s.end() ; it++)
	{
		cout << *it << " ";
	}
	
	return 0;
 } 

在这里插入图片描述

逆序遍历:

通过迭代器找到元素后,改变迭代器指向的元素,是可以直接改变字符串内容的

#include <iostream>
#include <string>
using namespace std;
int main()
{
 	string s = "abcdef"; 
 	for (string::iterator it = s.end() - 1; it >= s.begin(); --it) 
 	{ 
 		cout << *it << ' '; 
 	}
 	return 0;
}

在这里插入图片描述
在这里插入图片描述

通过迭代器找到元素后,改变迭代器指向的元素,是可以直接改变字符串内容的。

#include <iostream>
#include <string>
using namespace std;
int main()
{
 	string str = "abcdef"; 
 	cout << str << endl;
 	for (string::iterator it = str.begin(); it != str.end(); ++it) 
 	{ 
 		*it = 'x'; 
 	}
 	cout << str << endl;
 	return 0;
}

在这里插入图片描述

2.5 push_back()

push_back()用于在字符串尾部插一个字符。

在这里插入图片描述

使用示例:

#include <iostream>
#include<string> //添加string头?件
using namespace std;
int main()
{
 	//向空字符串中尾插字符
 	string s;
 	s.push_back('h');
 	s.push_back('e');
 	s.push_back('l');
 	s.push_back('l');
 	s.push_back('o');
 	cout << s << endl;
 	
 	
    //向非空字符串中尾插字符
 	string s1 = "hello ";
 	s1.push_back('w');
 	s1.push_back('o');
 	s1.push_back('r');
 	s1.push_back('l');
 	s1.push_back('d');
 	cout << s1 << endl;
 	//批量插入字符
 	string s2;
 	for (char c = 'a'; c <= 'f'; c++)
 	{
 		s2.push_back(c);
 	}
 	cout << s2 << endl;
 	return 0;
 }

运行结果:
在这里插入图片描述

2.6字符串的 += 和 + 运算

push_back()是用于在字符串后添加一个字符,然而部分情况下我们需要向原有的字符串后继续添加字符串。

其实string 类型的字符串是支持 + 和 += 运算的。这里的本质是 string 中重载了operator+=这个操作符。

具体使用请看下面的示例:


字符串s的末尾追加"world"

使用示例:

#include <iostream>
#include <string> //添加string头?件
using namespace std;
int main()
{
 	string s = "hello";
 	s += " world"; //字符串?双引号,等价于 s = s + " world"
 	cout << s << endl;
 
 	//除了+=操作,也可以使?'+'灵活进?字符串拼接
 	//1.尾部拼接

 	string s1 = "hello";
 	cout << s1 + " world" << endl; //s1仍然是"hello"
 
 	s1 = s1 + " world";
 	cout << s1 << endl; //s1是"hello world"
 
 
 	//2.头部拼接
 	string s2 = "hello";
 	s2 = "world " + s2 ; 
 	cout << s2 << endl; //s2为:"world hello"
 
 	return 0;
}

2.7 pop_back()

pop_back()用于删除字符串中尾部的一个字符。这个成员函数是在 C++11标准中引入的,有的编译器可能不支持。

使用示例:

int main()
{
 	string s = "hello";
 	cout << "s:" << s << endl;
 	//尾删
 	s.pop_back();
 	cout << "s:" << s << endl;
 	//尾删
 	s.pop_back();
 	cout << "s:" << s << endl;
 	return 0;
}

运行结果:
在这里插入图片描述

注意:

但是当字符串中没有字符的时候,再调用 pop_back()时,程序会出现异常。这种行为也是未定义行为,要避免这么使用

#include <iostream>
#include <string> //添加string头⽂件
using namespace std;
int main()
{
 	string s;
 	s.pop_back();
 	return 0;
}

在DevC++上,程序最终崩溃了:

在这里插入图片描述

为避免循环删除导致对空字符串进行尾删,可以将上面错误的代码改写成:

#include <iostream>
#include<string> //添加string头⽂件
using namespace std;
int main()
{
 	string s = "abc";
 	while(s.size() > 0) //通过size()函数来控制字符串的⻓度
 	{
 		s.pop_back();
 	}
 	return 0;
}

小提示:

不可对空字符串继续进行pop_back()操作,否则程序出现异常.

2.8 insert ( )

如果我们需要在字符串中间的某个位置插入一个字符串,怎么办呢?这时候我们得掌握一个函数就是insert

函数原型如下:

string& insert (size_t pos, const string& str); //pos位置前⾯插⼊⼀个string字符串
string& insert (size_t pos, const char* s); //pos位置前⾯插⼊⼀个C⻛格的字符串
string& insert (size_t pos, size_t n, char c);//pos位置前⾯插⼊n个字符c

代码举例:

//pos位置前?插??个string字符串
int main()
{
	string s = "abcdefghi";
	string str = "xxx";
	cout << s << endl;
	s.insert(3,str);
	cout << s << endl;
	return 0;
 } 

//pos位置前面插入一个C风格的字符串

int main()
{
	string s = "abcdefghi";
 	cout << s << endl;
 	s.insert(3, "xxx");
 	cout << s << endl;
	return 0;
}


//pos位置前面插入n个字符c

int main()
{
 	string s = "abcdefghi";
 	cout << s << endl;
 	s.insert(3, 3, 'x');
 	cout << s << endl;
	return 0;
}

2.9 find()

find()函数用于查找字符串中指定子串/字符,并返回子串/字符在字符串中第一次出现的位置。

size_t find (const string& str, size_t pos = 0) const;
//查找string类型的字符串str,默认是从头开始查找,pos可以指定位置开始

size_t find (const char* s, size_t pos = 0) const;
//查找C⻛格的字符串s,默认是从头开始查找,pos可以指定位置开始

size_t find (const char* s, size_t pos, size_t n) const;
//在字符串的pos这个位置开始查找C⻛格的字符串s中的前n个字符,

size_t find (char c, size_t pos = 0) const;
//查找字符c,默认是从头开始,pos可以指定位置开始

返回值:

  • 若找到。返回子串/字符在字符串中第一次出现的起始下标位置。

  • 若未找到。返回一个整数值 npos(针对 npos 的介绍会在下面给出)。通常判断 find()函数的返回值是否等于npos就能知道是否查找到子串或者字符。

代码举例1:

//代码1
#include <iostream>
#include <string> //添加string头文件
using namespace std;
int main()
{
 	string s = "hello world hello everyone";
 	string str = "llo";
 	//查找string类型的字符串
 	size_t n = s.find(str);
 	cout << n << endl;
 
	n = s.find(str, n + 1); //从n+1这个指定位置开始查找
 	cout << n << endl;
 
 	//查找C风格的字符串
 	n = s.find("llo");
 	cout << n << endl;
 
 	n = s.find("llo", n + 1); //从n+1这个指定位置开始查找
 	cout << n << endl;
 
 	return 0;
}

运行结果:

在这里插入图片描述

代码举例3:

#include <iostream>
#include <string> //添加string头文件
using namespace std;
int main()
{
	string s = "hello world hello everyone";
	size_t n = s.find('o');
	cout << n << endl;
	
	n = s.find('o', n + 1);
	cout << n << endl;
	return 0;
 } 

运行结果:
在这里插入图片描述

在字符串中查找字符或者字符串时,有可能查找不到,这时候 find 函数会返回 npos 这个值,该数字并不是一个随机的数字,而是 string 中定义的一个静态常量 npos。我们通常会判断 find 函数的返回值是否等于npos来判断,查找是否成功。

static const size_t npos = -1;
#include <iostream>
#include <string> //添加string头文件
using namespace std;
int main()
{
 	//注意:npos是string中定义的,使?npos需要带上string::指明是string类中的
 	cout << "npos:" << string::npos << endl; 
 	cout << "npos:" << (int)string::npos << endl; //由于npos是size_t的类型,所以直接打印会是一个很大的数,但其实是-1 
 	return 0;
}

打印出来看看:

在这里插入图片描述

所以我们想要知道找没找到,我们可以这样写:

int main()
{
	string s = "hello world hello everyone";
	size_t n = s.find("wu");
	if(n == string::npos)
	{
		cout << "找不到" << endl; 
	}
	else
	{
		cout << "找到了,n = " << n << endl; 
	}
	return 0;
 } 

2.10 substr()

substr()函数用于截取字符串中指定位置指定长度的子串。函数原型如下:

string substr (size_t pos = 0, size_t len = npos) const;
//pos 的默认值是0,也就是从下标为0的位置开始截取
//len 的默认值是npos,意思是⼀直截取到字符串的末尾
  • substr():如果函数不传参数,就是从下标为0的位置开始截取,直到结尾,得到的是整个字符串;
  • substr(pos):从指定下标pos位置开始截取子串,直到结尾;
  • substr(pos,len):从指定下标 pos 位置开始截取长度为len 的子串。

返回值类型:string,返回的是截取到的字符串,可以使用 string 类型的字符串接收。

代码举例:

#include <iostream>
#include<string> //添加string头?件
using namespace std;
int main()
{
 	string s = "hello world hello everyone";
 	string s1 = s.substr(7);
 	cout << s1 << endl;
 	
 	string s2 = s.substr(7, 6);
 	cout << s2 << endl;
 	return 0;
}

运行结果:
在这里插入图片描述

substr()和find()经常是配合使用的,find 负责找到位置,substr 从这个位置向后获得字符串。

#include <iostream>
using namespace std;
#include <string>
int main()
{
	string s = "hello world hello everyone";
	size_t n = s.find("world"); 
	string s1 = s.substr(n, 10);
	
	cout << s1 << endl;
	return 0;
}

运行结果:

在这里插入图片描述

2.11 string的关系运算

在实际写代码的过程中经常会涉及到两个字符串比较大小,比如:判断你输入的密码是否正确,就得将输入的密码和数据库中正确的密码比较。

那么**两个 string 类型字符串是否可以比较大小呢?**其实是可以的, C++中为string提供了一系列的关系运算。

2.11.1 支持的关系运算
string s1 = "abc";
string s2 = "abcd";
char s3[] = "abcdef"; //C⻛格的字符串
(1) s1 == s2
bool operator== (const string& lhs, const string& rhs);//使⽤⽅式:s1 == s2
bool operator== (const char* lhs, const string& rhs);//使⽤⽅式:s3 == s1
bool operator== (const string& lhs, const char* rhs);//使⽤⽅式:s1 == s3
(2) s1 != s2
bool operator!= (const string& lhs, const string& rhs);//使⽤⽅式:s1 != s2
bool operator!= (const char* lhs, const string& rhs);//使⽤⽅式:s3 != s1
bool operator!= (const string& lhs, const char* rhs);//使⽤⽅式:s1 != s3
(3) s1 < s2
bool operator< (const string& lhs, const string& rhs);//使⽤⽅式:s1 < s2
bool operator< (const char* lhs, const string& rhs);//使⽤⽅式:s3 < s1
bool operator< (const string& lhs, const char* rhs);//使⽤⽅式:s1 < s3
(4) s1 <= s2
bool operator<= (const string& lhs, const string& rhs);//使⽤⽅式:s1 <= s2
bool operator<= (const char* lhs, const string& rhs);//使⽤⽅式:s3 <= s1
bool operator<= (const string& lhs, const char* rhs);//使⽤⽅式:s1 <= s3
(5) s1 > s2
bool operator> (const string& lhs, const string& rhs);//使⽤⽅式:s1 > s2
bool operator> (const char* lhs, const string& rhs);//使⽤⽅式:s3 > s1
bool operator> (const string& lhs, const char* rhs);//使⽤⽅式:s1 > s3
(6) s1 >= s2
bool operator>= (const string& lhs, const string& rhs);//使⽤⽅式:s1 >= s2
bool operator>= (const char* lhs, const string& rhs);//使⽤⽅式:s3 >= s1
bool operator>= (const string& lhs, const char* rhs);//使⽤⽅式:s1 >= s3

上述的关系运算符的重载看着复杂,但是使用起来是非常简单的。

注:关于操作符的重载,只有深入学习 C + + \mathsf{C}\mathsf{+}\mathsf{+} C++的类和对象,才能深入理解和掌握,在竞赛的课程中不需要深入挖掘,会使用就行,但是要使用 C + + \mathsf{C}\mathsf{+}\mathsf{+} C++ 进行工程性开发的时候这部分知识一定要补上。

字符串的比较是基于字典序进行的,比较是对应位置上字符的ASCII值的大小;比较的不是字符串的长度。

比如:

1 “abc” < “aq” //'b’的ascii码值是小于’q’的
2 “abcdef” < “ff”" //'a’的ASCII码值是小于’f’的
3 “100” < “9” //'1’的ASCII码值是小于’9’的

2.11.2 代码举例1:
#include <iostream>
#include<string>
using namespace std;
int main()
{
 	string s1 = "hello world";
 	string s2 = "hello";
 	if (s1 == (s2 + " world")) 
 	{
 		cout << "s1 == s2" << endl;
 	}
 	else
 	{
 		cout << "s1 != s2" << endl;
 	}
 
 return 0;
}

运行结果:

在这里插入图片描述

2.11.3 代码举例2:
#include <iostream>
#include <string> 
using namespace std;
int main()
{
 	string s1 = "abcd";
 	string s2 = "abbcdef";
 	char s3[] = "bbc";
 	if (s1 > s2)
 		cout << "s1 > s2" << endl;
 	else
 		cout << "s1 <= s2" << endl;
 	if (s1 == s2)
 		cout << "s1 == s2" << endl;
 	else
 		cout << "s1 != s2" << endl;
 	if (s1 <= s3)
 		cout << "s1 <= s3" << endl;
 	else
 		cout << "s1 > s3" << endl;
 return 0;
}

运行结果:
在这里插入图片描述

2.12 和string相关的函数

2.12.1 stoi/stol
  • stoi 是将字符串转换成 int 类型的值
  • stol 是将字符串转换成 long int 类型的值
    这两个函数⾮常类型,这⾥以 stoi 为例讲解⼀下这⾥函数的使⽤⽅式。
    stoi 函数其实可以将⼀个 string 类型的字符串,转化为整型,函数原型如下:
int stoi (const string& str, size_t* idx = 0, int base = 10);
long stol (const string& str, size_t* idx = 0, int base = 10);

参数解读

  • str 表⽰被转换的 string 类型的字符串
  • idx 是⼀个输出型参数,也就是这个通过这个参数会带回⼀个值。 idx 是⼀个指针,需要在外边创建⼀个 size_t 类型的值,传递它的地址给 idx ,这个参数将会带回 str 中⽆法正确匹配数字的第⼀个字符的位置
  • base 表⽰被解析的字符串中数字的进制值,可能是 2 , 8 , 10 , 16 或者 0
    • 默认情况下这个值是 10 ,表⽰ 10 进制数字
    • 如果传递的是 2 ,表⽰被解析的字符串中是 2 进制的数字,最终会转换成 10 进制;
    • 如果传递的是 8 ,表⽰被解析的字符串中是 8 进制的数字,最终会转换成 10 进制;
    • 如果传递的是 16 ,表⽰被解析的字符串中是 16 进制的数字,最终会转换成 10 进制;
    • 如果传递的是 0 ,会根据字符串的内容的信息⾃动推导进制,⽐如:字符串中有 0x ,就认为是 16 进制, 0 开头会被认为是 8 进制,最终会转换成 10 进制。

代码举例1:

#include <iostream>
#include <string> 
using namespace std;
int main()
{
	string s = "11x22";
	size_t pos = 0;
	int n = stoi(s, &pos, 10);
	cout << n << endl; 
	cout << "pos = " << pos << endl;
	return 0;
 } 

借助这个代码我们也可以进一步理解第二个参数:

在这里插入图片描述

当然,如果我们不想用第二个参数,我们直接传一个0或NULL即可;

#include <iostream>
#include <string> 
using namespace std;
int main()
{
	string s = "11x22";
	size_t pos = 0;
	int n = stoi(s, 0, 10);
	cout << n << endl; 
	cout << "pos = " << pos << endl;
	return 0;
 } 

运行结果:

在这里插入图片描述
代码举例2:

#include <iostream>
#include<string> 
using namespace std;
int main()
{
 	size_t pos = 0;
 	string s1 = "11x34";
 	int ret1 = stoi(s1, &pos, 16);
 	cout << ret1 << endl;
 	cout << "pos:" << pos << endl;
 	string s2 = "11x34";
 	int ret2 = stoi(s2, &pos, 2);
 	cout << ret2 << endl;
 	cout << "pos:" << pos << endl;
 	string s3 = "0x11x34";
 	int ret3 = stoi(s3, &pos, 0);
 	cout << ret3 << endl;
 	cout << "pos:" << pos << endl;
 	return 0;
}

运行结果:
在这里插入图片描述

2.12.2 stod/stof

stod 是将字符串转换成 double 类型的值,函数原型如下,和 stoi 函数的⽐较的话,少了描述字符串中数字进制的参数,其他参数⼀致。 stof 是将字符串转换成 flaot 类型的值;

double stod (const string& str, size_t* idx = 0);
float stof (const string& str, size_t* idx = 0);

代码举例:

#include <iostream>
#include<string> 
using namespace std;
int main()
{
 	string s = "3.14x456";
 	double ret = stod(s, NULL);
 	cout << ret << endl;
 	return 0;
}

运行结果:
在这里插入图片描述

2.12.3 to_string

函数原型如下:

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

tostring 函数可以将数字转换成字符串,从上述函数原型的⻆度看的话,可以将整型、浮点型的数字转换成字符串的,使⽤起来也⾮常简单。

代码举例:

#include <iostream>
#include<string> 
using namespace std;
int main()
{
	string n = "pi is " + to_string(3.1415926);
	cout << n << endl;
	return 0;
}

运行结果:

在这里插入图片描述


总结

这期我们详细讲解了string在竞赛中常见的操作方法,下期我们会用相应的练习来进一步理解string,下期见;



http://www.kler.cn/a/534866.html

相关文章:

  • 接口对象封装思想及实现-笔记
  • Spring Boot - 数据库集成07 - 数据库连接池
  • 大模型综述一镜到底(全文八万字) ——《Large Language Models: A Survey》
  • 说一下JVM管理的常见参数
  • 解锁.NET Fiddle:在线编程的神奇之旅
  • Ruby 类和对象
  • PAT甲级1052、Linked LIst Sorting
  • TongSearch3.0.4.0安装和使用指引(by lqw)
  • python处理json文件
  • 人工智能丨PyTorch 计算机视觉
  • [创业之路-286]:《产品开发管理-方法.流程.工具 》-1- IPD两个跨职能团队的组织
  • (安全防御)防火墙安全策略部署
  • 玩转Amazon Bedrock基础模型:解锁图像风格混搭的无限可能
  • 【论文复现】基于适应度-距离平衡的自适应引导差分进化算法用于考虑可再生能源的安全约束最优潮流问题
  • 【Go语言快速上手】第一部分:Go 语言基础
  • Angular-hello world
  • 青少年编程与数学 02-008 Pyhon语言编程基础 22课题、类的定义和使用
  • C++【深入 STL--list 之 迭代器与反向迭代器】
  • 【鸿蒙HarmonyOS Next实战开发】视频压缩库VideoCompressor
  • Vue混入(Mixins)与插件开发深度解析
  • 常用抓包工具tcpdump、Fiddler、Charles、Wireshark 和 Sniffmaster 下载地址
  • 使用 CMake 自动管理 C/C++ 项目
  • C语言程序设计P6-5【应用指针进行程序设计 | 第五节】——指针与函数
  • OCR--光学字符识别
  • WebSocket推送数据快,条数多导致前端卡顿问题解决
  • 《Linux基础优化与常用软件包》