c++将数字移到一边,将字母移到另一边

c++ move numbers to one side and letters to other one

本文关键字:另一边 数字 c++      更新时间:2023-10-16

我通过解决问题来学习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;
}