[英]How to remove the Apostrophe at the from and the back from a string with c++
I ran into a little trouble with removing the first and last apostrophe from string.从字符串中删除第一个和最后一个撇号时遇到了一些麻烦。 I have a vector of string and some of them have apostrophe either at from or back of string.
我有一个字符串向量,其中一些在字符串的开头或后面有撇号。 For example, I have {'cause, 'til, holdin', don't} I want output like this {cause, til, holdin, don't} How do I do this?
例如,我有 {'cause, 'til, holdin', don't} 我想要像这样的 output {cause, til, holdin, don't} 我该怎么做?
You remove characters from strings with the .erase()
member function.您可以使用
.erase()
成员 function 从字符串中删除字符。 Example:例子:
#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;
}
I came up with following implementations, which covers the empty input scenario without invoking any undefined behaviour.我想出了以下实现,它涵盖了空输入场景而不调用任何未定义的行为。
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.