删除包含数字的字符串并将其他字符串转换为大写并用逗号分隔

Remove strings that contain digits and convert others in upper case and separate them with comma

我几乎完成了这个任务,但结果有点麻烦。下面是问题描述: 给定一个字符串向量,请实现以下2个函数对其进行处理和输出:

  1. process(): 删除包含数字的字符串并将其他字符串转换为大写

  2. output():打印字符串并用逗号分隔。 提示:

  3. 如果可能,就地操作矢量元素以避免复制矢量。

  4. 鼓励利用 STL functions/algorithms。 预期输出: ==========================================

    之前:abc、123、456、xyz

    之后:ABC、XYZ

但是我的代码导致输入不符合预期

before process: abc, 123, 456, xyz,
after process: ABC, XYZ,

请告诉我如何在两种情况下删除字符串末尾的逗号before/after 过程

这是我的代码:

#include <algorithm> 
#include <cctype> 
#include <iostream> 
#include <vector> 
 

void process(std::vector<std::string>& v)
{
    
    // Remove strings that contain digits
    for(std::string &s : v)
        s.erase(std::remove_if(std::begin(s), std::end(s), 
                           [](unsigned char ch) { return std::isdigit(ch); }), 
            s.end()); 
 
    // Convert other characters into upper case
// std::toupper has several overloads
// template <class charT> charT toupper(charT, const locale&)
// int toupper(int ch)
// So taking its address might be complicated.
// We can use lambda to let compiler found the right overload:
// (In addition, as char might be signed or not, and toupper expects unsigned char value (or EOF))
    for(std::string &s : v)
    {
        std::transform(s.begin(), s.end(), s.begin(), 
        [](unsigned char c){ return std::toupper(c); }); 
    }
    std::cout << '\n';
}

void output(std::vector<std::string>& v) 
{
    for(std::string &str : v)
        if(str != "[=11=]")
            std::cout << str << ", "; 
        
}

int main() 
{ 
    std::vector<std::string> v = { "abc", "123", "456", "xyz" };
    std::cout << "Before: "; output(v);
    process(v);
    std::cout << "After: "; output(v);
    return 0;
} 

有时候,好的旧语法是一件好事。

void output(std::vector<std::string>& v)  {
    
    // clean array
    size_t n = v.size();
    while(n--) if(v[n] == '[=10=]') v.erase(v.begin() + n);
    
    // print words
    for(size_t i = 0; i < v.size(); ++i) {
        std::cout << v[i];
        if(i < (v.size() - 1) std::cout << ", "; 
    }
}

另一种方法

void output(std::vector<std::string>& v)  {

    // clean array
    size_t n = v.size();
    while(n--) if(v[n] == '[=11=]') v.erase(v.begin() + n);

    // print words
    size_t max = v.size() - 1;

    for(size_t i = 0; i < max; ++i) 
        std::cout << v[i] << ", "; 

    std::cout << v[max];
}

打印向量的第一个元素。使逗号与下一个元素一起打印。

void output(const std::vector<std::string> &v) {
    // find 1st not-empty string
  auto iter = std::find_if(v.cbegin(), v.cend(),
                           [](const auto &s) { return !s.empty(); });

  if (iter == v.cend()) {
    return;  // return if all of v are empty strings
  }

  std::cout << *iter;  // print 1st one
  ++iter;

  // print comma and next string if not empty
  for (; iter != v.cend(); ++iter) {
    if (!iter->empty()) {
      std::cout << ", " << *iter;
    }
  }

  std::cout << '\n';
}