2016-02-27 62 views
1

我想弄清楚如何alphabetize包含单词和数字的单个字符串。正如你在下面看到的,我试过使用isdigit,但其中一些数字是负数,所以我的代码总是错的。此外,我的代码将字符串拆分为字母串分开的子字符串,但我不知道如何分别字母化所有单词,将它们放回到它们在矢量中的位置,然后单独将所有数字字母化,然后放回进入他们的位置。有人可以帮忙吗?Alphabetize字符串与文字和数字

编辑:

样品输入#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++; 
    } 
} 
+0

请将样本输入,预期输出和观测输出。 –

+0

你可以分享样本输入输出吗?需要确定你正在尝试做什么。 –

+0

'char * a = new char [numbers [i] .size()+ 1];'为什么? – PaulMcKenzie

回答

0

我的2p。

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 
} 
+0

感谢您的帮助。我觉得这个代码是最易读和最容易遵循的! – Jeremy

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::sort排序的字符串的int std::vector

// include <algorithm> // sort 

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

的其他解决办法是分裂的两个vector单独vector秒。一个字符串和一个数字和他们sperately排序:

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具有comperator功能太:

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; 
} 
+0

感谢您的帮助!我唯一看到的是这个代码不会将单词/数字分别放回属于单词和数字的位置。 – Jeremy

+0

@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是该类型的最大元素,它被插入到后面。

It lives!

案例事项这种比较('a' != 'A'),但如果它不应该的问题,增加了修复程序,很容易。

+0

对不起,但是名为sorted的向量是从哪里来的呢? – Jeremy

+0

@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++] << ' '; 
    } 
} 
+0

这种方式看起来更好,但请提一下,如果您无法事先预测元素的数量,我会相应地修改代码。 – anukul

+0

我无法预测元素的数量 – Jeremy

+0

好的,我已经做出了修改。现在应该工作正常。 – anukul