c++ 如何根据最后一个字符串将字符串拆分为两个字符串'.'
c++ How to split string into two strings based on the last '.'
我想根据最后一个字符串将字符串分成两个单独的字符串'.'
例如,abc.text.sample.last
应该变得abc.text.sample
。
我尝试使用boost::split
但它给出的输出如下:
abc
text
sample
last
再次构造字符串添加'.'
将不是好主意,因为顺序很重要。做到这一点的有效方法是什么?
像
rfind
+ substr
这样简单的东西
size_t pos = str.rfind("."); // or better str.rfind('.') as suggested by @DieterLücking
new_str = str.substr(0, pos);
std::string::find_last_of
将为您提供字符串中最后一个点字符的位置,然后您可以使用该位置相应地拆分字符串。
利用函数 std::find_last_of 然后是 string::substr 来获得所需的结果。
从右开始搜索第一个"."。使用 substr
提取子字符串。
另一种可能的解决方案,假设您可以更新原始字符串。
-
取字符指针,从最后一个遍历。
-
找到第一个"."时停止,将其替换为"\0"空字符。
-
将字符指针分配给该位置。
现在您有两个字符串。
char *second;
int length = string.length();
for(int i=length-1; i >= 0; i--){
if(string[i]=='.'){
string[i] = ' ';
second = string[i+1];
break;
}
}
我没有包括诸如"."是否最终或任何其他测试用例。
如果你想使用boost,你可以试试这个:
#include<iostream>
#include<boost/algorithm/string.hpp>
using namespace std;
using namespace boost;
int main(){
string mytext= "abc.text.sample.last";
typedef split_iterator<string::iterator> string_split_iterator;
for(string_split_iterator It=
make_split_iterator(mytext, last_finder(".", is_iequal()));
It!=string_split_iterator();
++It)
{
cout << copy_range<string>(*It) << endl;
}
return 0;
}
输出:
abc.text.sample
last
相关文章:
- 两个字符串在 c++ 中不相等
- 在C++的两个字符串中连接以逗号分隔的唯一值
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 比较两个字符串后卡在无限循环中
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 我需要帮助在一个类中输入两个字符串并获取其输出
- 这两个C++语句连接字符串有什么区别?
- 两个字符串之间的数学运算
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 有没有办法我可以在 C++ 中使用 if 语句来说明如果一个字符串不是两个名称的 eqal,它会给出一个输出,ATM i
- 如何在 main 函数中输出两个新字符串C++?
- sscanf() 有两个字符串参数
- 我的字符串数组一次打印出前两个字符串
- 两个 c++ 字符串上的异或
- 函数返回两个字符串的第一个常用字符
- 目标是找到两个 c 字符串之间的公共前缀(必须使用特定的函数标头)