Как удалить апостроф в и из задней части строки с C ++ - PullRequest
0 голосов
/ 31 октября 2019

У меня возникла небольшая проблема с удалением первого и последнего апострофа из строки. У меня есть вектор строки, и некоторые из них имеют апостроф либо в начале, либо в конце строки. Например, у меня есть {'потому что,' пока, держу, не надо}, я хочу вывод, как это {потому что, пока, держу, не делаю} Как мне это сделать?

Ответы [ 2 ]

0 голосов
/ 31 октября 2019

Я придумал следующие реализации, которые охватывают пустой сценарий ввода без вызова какого-либо неопределенного поведения.

#include <vector>
#include <string>
#include <iostream>
#include <algorithm>

std::vector<std::string> contents = {"'cause", "'til", "holdin'", "don't", ""};

void impl1() {
    for(auto & content:contents){
        if(!content.empty() && (*content.begin()) == '\''){
            content.erase(content.begin());
        }

        if(!content.empty() && content.back() == '\''){
            content.pop_back();
        }

        std::cout << content << " " << std::endl;
    }
}

void impl2(){
    auto erase_if = [](auto& container, auto&& itr, auto val){
        if(!(itr == std::end(container)) && ((*itr) == val)){
            container.erase(itr);
        }  
    };   
    for(auto & content: contents){
        erase_if(content, content.begin(), '\'');
        erase_if(content, std::string::iterator{&content.back()}, '\'');

        // print trimmed output
        std::cout << content << " " << std::endl;
    }
}


int main(void){
    //impl1();
    impl2();
    return 0;
}
0 голосов
/ 31 октября 2019

Вы удаляете символы из строк с помощью функции-члена .erase(). Пример:

#include <iostream>
#include <string>
#include <vector>

void trim_inplace(std::string &s, char c) {
  if (s.size() >= 2) {
    auto it = s.begin();
    if (*it == c) {
      s.erase(it);
    }
    it = s.end() - 1;
    if (*it == c) {
      s.erase(it);
    }
  }
}

int main() {
  std::vector<std::string> foo{"'cause", "'til", "holdin'", "don't"};
  for (auto &s : foo) {
    std::cout << s << " -> ";
    trim_inplace(s, '\'');
    std::cout << s << '\n';
  }
  return 0;
}
...