2016-03-04 119 views
3

我想根据最后的'.' 将字符串拆分为两个单独的字符串。例如,abc.text.sample.last应该变为abc.text.sampleC++如何根据最后的'。'将字符串拆分为两个字符串。

我尝试使用boost::split但如下给出输出:

字符串再次添加 '.'
abc 
text 
sample 
last 

建设不会是好主意,因为顺序问题。 什么将是有效的方式来做到这一点?

回答

6

std::string::find_last_of将为您提供字符串中最后一个点字符的位置,然后您可以使用该位置来相应地拆分字符串。

+0

谢谢你,将使用 – Namitha

2

搜索第一个'。'从右边开始。使用substr来提取子字符串。

5

一些简单的rfind + substr

size_t pos = str.rfind("."); // or better str.rfind('.') as suggested by @DieterLücking 
new_str = str.substr(0, pos); 
+4

'str.rfind( '');一个'单个字符 –

+0

这(经修改)是正确的答案。 'rfind('。')'是比'find_last_not_of'更好的选择;后者必须做一些额外的轮子旋转,因为它可以搜索多个字符。 –

0

还有一个可能的解决方案,假设你可以更新原始的字符串。

  1. 带上char指针,从最后遍历。

  2. 第一次停止时'。'发现,用'\ 0'空字符替换它。

  3. 将字符指针指定给该位置。

现在你有两个字符串。

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; 
} 
} 

我还没有包含像'。'这样的测试用例。是最后的,还是其他的。

0

如果你想使用升压,你可以试试这个:

#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 
相关问题