c++将数字移到一边,将字母移到另一边
c++ move numbers to one side and letters to other one
我通过解决问题来学习C++。我需要制作一个程序,通过将数字移动到另一边,对用户输入的文本进行排序。
例如:字符串"a13Bc1de2F G.!Hi8Kl90"-应该看起来像:"aBDeFGHiKl.!1312890"
我只是设法制作了一个程序,将文本按字母顺序排序。我想得到一些指导。我想我需要检查每个字符(如果是字母或数字),然后转移到其他字符串,但我不确定如何制作
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str1;
cout << " Hi user! n"
"Imput some mess here: n";
cin >> str1;
sort(str1.begin(), str1.end());
cout << "Now it's not a mess : n" << str1 << endl;
system("pause");
return 0;
}
下面的代码应该可以随心所欲。我已经尽可能少地更改了原始代码。
主机功能为move_digits_to_right
。我们使用cctype
库中的isdigit
函数,该函数检查给定字符是否为数字。如果是,我们将其附加到digitVec
向量,否则,我们将它附加到nonDigitVec
向量。最后,我们返回一个以非数字字符开头、后跟数字字符的字符串,同时保留它们在原始字符串中的出现顺序。
在main
函数中,我已将cin >> str1
行更改为getline(cin, str)
。否则,对于"a13Bc1de2F G.! Hi8Kl90"
的示例输入,只有"a13Bc1de2F"
部分将被读取到str1
中。使用getline(cin, str)
可以读取整行输入。
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
using namespace std;
string move_digits_to_right(const string& s)
{
vector<char> digitVec, nonDigitVec;
int len = (int) s.size();
for (int i = 0; i < len; i++) {
if (isdigit(s[i])) {
digitVec.push_back(s[i]);
} else {
nonDigitVec.push_back(s[i]);
}
}
return string(nonDigitVec.begin(), nonDigitVec.end()) +
string(digitVec.begin(), digitVec.end());
}
int main()
{
string str1, output;
cout << " Hi user! n"
"Imput some mess here: n";
getline(cin, str1);
output = move_digits_to_right(str1);
cout << "Now it's not a mess : n" << output << endl;
system("pause");
return 0;
}
相关文章:
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 如何使'='重载在'='的另一边工作
- 如何在C++中创建 2d 数组,其中一部分包含循环计数器,另一部分包含数字列表?
- 根据另一个数字的可整除性返回子数组中的索引
- C++ 从一个数字向上计数到另一个数字
- 如何在另一边创建重载+
- 为什么数组在一个文件中打印,但在发送到另一个文件时却缺少数字
- 将映射的每个键中的数字数据与另一个数值进行比较
- 更快的方法将数字从范围转换为另一个范围
- 维护多集中数字的排序列表和另一个集合中的累积总和
- 程序检查是否包含另一个数字
- 如何计算一个数字到另一个数字中的数量
- 将一个数组的内容复制到另一个数组时出现问题..得到奇怪的数字
- 找到最大.任何给定数字的功率值小于另一个给定数字
- BITWISE-如何检查二进制号是否包含另一个数字
- 在另一个字符串中查找一串数字
- c++将数字移到一边,将字母移到另一边
- 查找存储在一个数组中的数字组合,并将这些组合存储在另一个数组
- 找到最接近另一个数字 c++ 的数字
- 如果我将数字存储为整数数据类型,如何检查另一个数字中是否存在一个数字