简介
在这篇文章中,我们将学习如何使用C++从一个字符串中提取整数并将其存储在一个向量中。
首先,我们来定义向量和字符串。向量是数组的一个更稳健的版本,与数组相比,更不容易出错。与数组不同的是,数组是静态的,其大小需要事先声明,向量是动态的,可以自行调整大小。使用向量的好处是它可以为增长分配空间,然而,正因为如此,与使用数组相比,它们也会消耗更多的内存。 字符串是一个一维数组,代表了像整数和字母一样的字符序列。
现在让我们来看看一个示例问题:
Input: String = "There are 5 dogs and 3 cats."
Output: 5 3
Input: String = " OpenGenus 11 22 234 test"
Output: 11 22 234
为了从字符串中提取整数,我们将使用stringstream。Stringstream是C++中的一个流类,可以让你对字符串进行操作。字符串流允许你读取、提取或插入字符串对象。我们将把字符串传递给stringstream,使用一个循环,我们可以查看每个字,并检查它是否是一个整数。如果检测到一个整数,它将被追加到一个向量中。循环将继续下去,直到它到达字符串的末端。
算法
-
将字符串传递给stringstream
-
在一个循环中,遍历每个字
-
检查该字是否是一个整数
-
在向量中存储数值
复杂程度
- 最坏情况下的时间复杂度。
**Θ(N)** - 平均情况下的时间复杂度。
**Θ(N)** - 最佳情况下的时间复杂度。
**Θ(1)**
实现方式
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
stringstream ss;
string str = " OpenGenus 11 22 234 test";
// store the string to string stream
ss << str;
//declare vector
vector< int > intValues;
string temp;
int number;
while (!ss.eof()) {
//for getting each word in the string
ss >> temp;
// check for integers
if (stringstream(temp) >> number){
// if it is an integer value will be pushed to the vector
intValues.push_back(number);
}
}
// print values inside the vector
for (int i=0; i<intValues.size(); i++){
cout<<intValues[i] << " ";
}
return 0;
}
输出:
应用
-
可用于从用户输入的字符串中获取整数值。
-
当要存储的值的大小未知时,可以使用矢量。
问题1
你用什么命令将数值追加到一个向量中:
front()
push_back()
pop_back()
assign()
push_back()函数用于将元素从后面推入一个向量。
问题2
向量是静态的还是动态的?
静态
取决于实现方式
都是
动态的
向量是动态的,可以自行调整大小。
通过OpenGenus的这篇文章,你一定对如何使用C++从字符串中提取整数并存储在向量中有了完整的认识。