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
构造字符串再次添加 '.'
不是一个好主意,因为顺序很重要。
执行此操作的有效方法是什么?
搜索第一个“.”从右边开始。使用substr
提取子串。
std::string::find_last_of
将为您提供字符串中最后一个点字符的位置,然后您可以使用它来相应地拆分字符串。
利用函数std::find_last_of and then string::substr达到预期效果。
像 rfind
+ substr
这样简单的东西
size_t pos = str.rfind("."); // or better str.rfind('.') as suggested by @DieterLücking
new_str = str.substr(0, pos);
另一种可能的解决方案,假设您可以更新原始字符串。
取char指针,从最后开始遍历
当第一个 '.' 时停止找到,用'\0'空字符替换。
将字符指针分配给该位置。
现在你有两个字符串。
char *second;
int length = string.length();
for(int i=length-1; i >= 0; i--){
if(string[i]=='.'){
string[i] = '[=10=]';
second = string[i+1];
break;
}
}
我没有包含像 if '.' 这样的测试用例是最后,还是其他。
如果你想使用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
我想根据最后一个'.'
将字符串拆分成两个单独的字符串
例如,abc.text.sample.last
应该变成 abc.text.sample
。
我尝试使用 boost::split
但它给出的输出如下:
abc
text
sample
last
构造字符串再次添加 '.'
不是一个好主意,因为顺序很重要。
执行此操作的有效方法是什么?
搜索第一个“.”从右边开始。使用substr
提取子串。
std::string::find_last_of
将为您提供字符串中最后一个点字符的位置,然后您可以使用它来相应地拆分字符串。
利用函数std::find_last_of and then string::substr达到预期效果。
像 rfind
+ substr
size_t pos = str.rfind("."); // or better str.rfind('.') as suggested by @DieterLücking
new_str = str.substr(0, pos);
另一种可能的解决方案,假设您可以更新原始字符串。
取char指针,从最后开始遍历
当第一个 '.' 时停止找到,用'\0'空字符替换。
将字符指针分配给该位置。
现在你有两个字符串。
char *second;
int length = string.length();
for(int i=length-1; i >= 0; i--){
if(string[i]=='.'){
string[i] = '[=10=]';
second = string[i+1];
break;
}
}
我没有包含像 if '.' 这样的测试用例是最后,还是其他。
如果你想使用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