我想根据最后的'.'
将字符串拆分为两个单独的字符串。例如,abc.text.sample.last
应该变为abc.text.sample
。C++如何根据最后的'。'将字符串拆分为两个字符串。
我尝试使用boost::split
但如下给出输出:
'.'
的
abc
text
sample
last
建设不会是好主意,因为顺序问题。 什么将是有效的方式来做到这一点?
我想根据最后的'.'
将字符串拆分为两个单独的字符串。例如,abc.text.sample.last
应该变为abc.text.sample
。C++如何根据最后的'。'将字符串拆分为两个字符串。
我尝试使用boost::split
但如下给出输出:
'.'
的
abc
text
sample
last
建设不会是好主意,因为顺序问题。 什么将是有效的方式来做到这一点?
std::string::find_last_of
将为您提供字符串中最后一个点字符的位置,然后您可以使用该位置来相应地拆分字符串。
搜索第一个'。'从右边开始。使用substr
来提取子字符串。
利用功能std::find_last_of然后string::substr来实现所需的结果。
一些简单的rfind
+ substr
size_t pos = str.rfind("."); // or better str.rfind('.') as suggested by @DieterLücking
new_str = str.substr(0, pos);
'str.rfind( '');一个'单个字符 –
这(经修改)是正确的答案。 'rfind('。')'是比'find_last_not_of'更好的选择;后者必须做一些额外的轮子旋转,因为它可以搜索多个字符。 –
还有一个可能的解决方案,假设你可以更新原始的字符串。
带上char指针,从最后遍历。
第一次停止时'。'发现,用'\ 0'空字符替换它。
将字符指针指定给该位置。
现在你有两个字符串。
char *second;
int length = string.length();
for(int i=length-1; i >= 0; i--){
if(string[i]=='.'){
string[i] = '\0';
second = string[i+1];
break;
}
}
我还没有包含像'。'这样的测试用例。是最后的,还是其他的。
如果你想使用升压,你可以试试这个:
#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
谢谢你,将使用 – Namitha