从字符串中删除字符的第一个和最后一个实例
Remove first and last instance of a char from a string
我有一个.ini文件,我在其中声明了如下部分:
[章节名称]
我想摆脱"["和"]"以仅在部分名称中读取,目前我正在使用它来实现我想要的:
line.substr(1, line.size() - 2);
但这只会删除第一个和最后一个角色,无论它们是什么。我正在寻找一种优雅的方式来删除第一次出现的"["和最后一次出现的"]"。提前感谢!
编辑:我尝试使用这个:
void TrimRight(std::string str, std::string chars)
{
str.erase(str.find_last_not_of(chars) + 1);
}
void TrimLeft(std::string str, std::string chars)
{
str.erase(0, str.find_first_not_of(chars));
}
TrimLeft(line, "[");
TrimRight(line, "]");
但这并不是出于某种奇怪的原因删除它们......
你可以使用字符串 front() 和 back() 成员函数:
#include <iostream>
#include <string>
int main() {
std::string s = "[Section]";
if (s.front() == '[' && s.back() == ']') {
s.erase(0, 1);
s.pop_back();
}
std::cout << s;
}
或者,如果您希望删除其中之一:
if (s.front() == '[') {
s.erase(0, 1);
}
if (s.back() == ']') {
s.pop_back();
}
.pop_back()函数删除最后一个字符。您的函数按值而不是引用接受参数。以下是函数变体:
一个void
函数,您可以在其中通过引用传递参数:
void trimstr(std::string& s) {
if (s.front() == '[' && s.back() == ']') {
s.erase(0, 1);
s.pop_back();
}
}
和返回std::string
的函数:
std::string gettrimmed(const std::string& s) {
std::string temp = s;
if (temp.front() == '[' && temp.back() == ']') {
temp.erase(0, 1);
temp.pop_back();
}
return temp;
}
使用string::find_first_of()
和string::find_last_of()
查找两个字符的位置。然后获取这两个位置之间的子字符串:
int main() {
std::string s("[SectionName]");
size_t first = s.find_first_of('[');
size_t last = s.find_last_of(']');
if (std::string::npos != first && std::string::npos != last)
{
std::cout << s.substr(first + 1, last - first - 1);
}
return 0;
}
演示
相关文章:
- 获取向量C++中第一个值和最后一个值的和
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 在类的第一个/最后一个实例存在之前/之后调用一对函数.有没有更好的方法?
- 查询事件日志.如何查询才能单独获取第一个和最后一个事件?
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 如何打印第一个和最后一个元素的和,然后打印第二个和倒数第二个元素的总和,依此类推
- 使用 STL 交换堆栈 C++ 中的第一个和最后一个元素
- 使用数组将最后一个最大值更改为第一个最小值
- "如何使用C++将字符串的第一个和最后一个索引返回到向量中?
- 查找数组的第一个和最后一个索引,其中 from 和 to 元素的顺序总和最大
- 数组:如何在指定索引之前显示数组的第一个和最后一个元素以及数组元素的差异?
- 输入文件中的第一个字符是输出文件中的最后一个字符,反之亦然
- 在向量C++中查找特定的第一个和最后一个索引<float>
- 如何使用第一个、中间和最后一个元素的中位数正确分区?
- 计算第一个和最后一个元素绝对差值较小的子序列 <= K
- COUT:最后一个字符串覆盖第一个字符串
- 获取第 n 项与 std::set 中第一个/最后一个的偏移量
- 如何使用递归返回单链表中的第n个最后一个元素
- 当第一个<=最后一个不满足时,C++标准对算法有什么看法?
- c++函数——哪个日期是第一个/最后一个