按字母顺序排列包含单词和数字的字符串

3
我正在尝试弄清楚如何按字母顺序排列一个包含单词和数字的字符串。正如您下面所看到的,我已经尝试使用 isdigit 但是一些数字是负数,所以我的代码总是不正确的。此外,我的代码将字符串拆分为子字符串,这些子字符串按照字母顺序排序,但我不知道如何单独按字母顺序排序所有单词,将它们放回它们在向量中的位置,然后单独按字母顺序排序所有数字,并将它们放回它们在向量中的位置。谁能帮帮我?
编辑:
样本输入#1:
4 dog 1 -3 0 cat 3

样例输出 #1:

-3 cat 0 1 3 dog 4

样例输入 #2:

tom 4 0 9 kid pie 1

示例输出 #2:

kid 0 1 4 pie tom 9

到目前为止,我的代码看起来是这样的:
vector<string> numbers; 
string str;
string x;                   
getline (cin, str);
stringstream ss(str);
while (ss >> x){
   numbers.push_back(x);
}

if (numbers.size()==1){
    cout << numbers[0] << endl;
    return 0;
}

vector<int> results(numbers.size());
for (int i=0;i<numbers.size();i++){
    char *a=new char[numbers[i].size()+1];
    a[numbers[i].size()]=0;
    memcpy(a,numbers[i].c_str(),numbers[i].size());
    if(isdigit(*a)==0)
    {
        results[i]=1;
    } else{
        results[i]=0;
    }
}

int j=0;
while (j<numbers.size()){
    int k=j+1;
    while (k<numbers.size()){
        while (results[j]==results[k]){
            sort(numbers.begin()+j,numbers.begin()+k+1);
            k++;
        }
        j=k;
        k=numbers.size();
    }
    if(j==numbers.size()){
        for (int i=0; i<numbers.size();i++){
            cout << numbers[i] << " ";
        }
        j++;
    }
}

请发布样本输入、期望输出和观察到的输出。 - R Sahu
你能分享样例输入输出吗?需要确保你想做什么。 - usamazf
char *a=new char[numbers[i].size()+1]; 这是为什么? - PaulMcKenzie
样例输出让我比之前更加困惑这个问题。我没有看出单词应该与数字有何关系。 - Weak to Enuma Elish
1
@Jeremy 为什么你不直接使用 std::string 呢?完全没有必要做你正在做的事情。此外,你还引入了内存泄漏问题。string a = numbers[i]; - PaulMcKenzie
显示剩余4条评论
4个回答

2

首先,您需要一个函数来确定一个字符串是否为数字。为此,请使用strtol

#include <stdlib.h> // strtol

bool is_number( const std::string &str, long &num )
{
    char *p;
    num = strtol( str.c_str(), &p, 10 );
    return *p == '\0';
}

在第二个函数中使用此函数,该函数确定字符串a是否小于字符串b

#include <tuple>

bool sortFunc( const std::string &a, const std::string &b )
{ 
    long numA;
    long numB;
    bool is_a_num = is_number( a, numA );
    bool is_b_num = is_number( b, numB );
    return std::make_tuple( !is_a_num, numA, a ) < std::make_tuple( !is_b_num, numB, b );                                      
}

使用 std::sortstd::vector 中的字符串进行排序。

// include <algorithm> // sort

std::vector< std::string > numbers;
.... 
std::sort( numbers.begin(), numbers.end(), sortFunc );

另一种解决方案是将 vector 分成两个独立的 vector,一个用于字符串,一个用于数字,并分别进行排序:
std::vector< std::string > numbers;
....
std::vector< std::string > vStr;
std::vector< long > vNum;
for ( std::string &str: numbers )
{
    long num;
    if ( is_number( str, num )
        vNum.push_back( num );
    else
        vStr.push_back( str);
}
std::sort( vNum.begin(), vNum.end() );
std::sort( vStr.begin(), vStr.end() );

如果你想知道原始vector中每个字符串或数字的位置,可以使用std::map

#include <map>

std::vector< std::string > numbers;
....
std::map< std::string, size_t > mapStr; // map string to index of string in vector numbers
std::map< long, size_t > mapNum;        // map number to index of number in vector numbers
for ( size_t index = 0; index < numbers.size(); index ++ )
{
    long num;
    if ( is_number( numbers[index], num ) )
        mapNum.emplace( num, index );
    else
        mapStr.emplace( numbers[index], index );
}

for ( auto & pa : mapNum )
    std::cout << pa.first << " pos " << pa.second << std::endl;
for ( auto & pa : mapStr )
    std::cout << pa.first.c_str() << " pos " << pa.second << std::endl;

当然你也可以使用带有比较函数的单个std::map

std::vector< std::string > numbers;
....
std::map< std::string, size_t, bool(*)(const std::string &a, const std::string &b) > mapN( sortFunc );
for ( size_t index = 0; index < numbers.size(); index ++ )
    mapN.emplace( numbers[index], index );

for ( auto & pa : mapN )
    std::cout << pa.first << " pos " << pa.second << std::endl;

您也可以将std::tuple作为std::map的键:

std::vector< std::string > numbers;
....
std::map< std::tuple< bool, long, std::string>, size_t > mapTupleN;
for ( size_t index = 0; index < numbers.size(); index ++ )
{
    long num;
    bool is_num = is_number( numbers[index], num );
    mapTupleN.emplace( std::make_tuple( !is_num, num, numbers[index] ), index );
}
for ( auto & pa : mapTupleN )
{
    if ( !std::get<0>(pa.first) )
        std::cout << std::get<1>(pa.first) << " is number at position " << pa.second << std::endl;
    else
        std::cout << std::get<2>(pa.first).c_str() << " is string at position " << pa.second << std::endl;
}

谢谢你的帮助!我唯一看到的问题是,这段代码不会将单词和数字分别放回它们所属的位置。 - Jeremy
@Jeremy 如果你想知道原始向量中每个字符串或数字的位置,可以使用 std::map。请查看我回答的最后一部分。 - Rabbid76

0

在读取元素时进行排序可能会更容易。

std::string input;
std::getline(std::cin, input);
std::stringstream ss(input);
std::vector<std::string> sorted;

while (ss >> input)
{
    bool alpha = 0 < std::isalpha(input[0]); //if it is a word
    for (std::size_t i = 0, e = sorted.size(); i != e; ++i)
    {
        if ((!!std::isalpha(sorted[i][0]) == alpha) && (alpha ? (input < sorted[i]) : (std::stoi(input) < std::stoi(sorted[i])))) //if input is <
            std::swap(sorted[i], input); //exchange places
    }
    sorted.emplace_back(std::move(input)); //insert input at end
}

每次while循环迭代,它都会检查第一个字符是否为字母。如果是字母,则必须是单词,否则就是数字。然后,对于先前扫描的每个元素,它都会检查它们是否是相同类型(字母/字母,数字/数字)。如果它们都是单词,它只是比较它们。如果它们是数字,则使用stoi将它们转换为整数并进行比较。如果比较得出input小于元素,则交换元素与input。在for循环结束时,input是该类型的最大元素,并且被插入到后面。

它还活着!

在此比较中大小写有区分('a' != 'A'),但如果不应考虑大小写,则添加修复程序很容易。


抱歉,请问名称为sorted的向量从哪里来? - Jeremy
@Jeremy 我意识到我漏掉了那个部分,所以我已经编辑了变量声明。也许你需要重新加载页面。 - Weak to Enuma Elish

0

我的见解。

std::string alphabetize(const std::string& s)
{
    // string parts here
    std::vector<std::string> a;

    // integer parts here
    std::vector<int> n;

    // remember the order of the input types (true = integer, false = string)
    std::vector<bool> type_is_int_list;

    // wrap input in a stream for easy parsing
    std::istringstream iss(s);

    // somewhere to read each part into
    std::string item;

    // extract one space-separated part at a time
    while(iss >> item)
    {
        int i;
        if(std::istringstream(item) >> i) // is item an integer?
        {
            n.push_back(i);
            type_is_int_list.push_back(true);
        }
        else
        {
            a.push_back(item);
            type_is_int_list.push_back(false);
        }
    }

    // sort both string and integer vectors
    std::sort(a.begin(), a.end());
    std::sort(n.begin(), n.end());

    // a place to rebuild the output from the input
    std::ostringstream oss;

    // keep track of where we are in each vector
    auto a_iter = a.begin();
    auto n_iter = n.begin();

    // element separator
    std::string sep;

    // scan originally-ordered list of types to rebuild positions
    for(bool type_is_int: type_is_int_list)
    {
        if(type_is_int)
            oss << sep << *n_iter++; // add next sorted number to output
        else
            oss << sep << *a_iter++; // add next sorted string to output

        sep = " "; // after first item need space separator
    }

    return oss.str(); // return the reconstructed string
}

感谢您的帮助。我觉得这段代码最易读和最容易理解! - Jeremy

0
怎么样?
#include "iostream"
#include "algorithm"
#include "string"
#include "vector"
#include "cctype"
#include "unordered_map"
using namespace std;

int main()
{
    vector <string> all, s;
    vector <int> n;
    unordered_map <int, bool> number;
    string x;
    getline(cin, x);
    int prev=0;
    for (int i=0; i<x.length(); i++)
    {
        if (x[i]==' ')
        {
            all.push_back(x.substr(prev, i-prev+1));
            prev=i+1;
        }
    }
    all.push_back(x.substr(prev));
    for (int i=0; i<all.size(); i++)
    {
        if (isdigit(all[i].c_str()[0]) || isdigit(all[i].c_str()[1]))
        {
            n.push_back(atoi(all[i].c_str()));
            number[i]=1;
        }
        else s.push_back(all[i]);
    }
    sort(s.begin(), s.end());
    sort(n.begin(), n.end());
    for (int i=0, j=0, k=0; i<all.size(); i++)
    {
        if (number[i]) cout << n[j++] << ' ';
        else cout << s[k++] << ' ';
    }
}

这样看起来更好,但如果您无法预测元素的数量,请说明,我会相应修改代码。 - anukul
我无法预测元素数量。 - Jeremy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接