簡體   English   中英

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

構造字符串添加'.' 因為序列很重要,所以不會是個好主意。 這樣做的有效方法是什么?

std::string::find_last_of將為您提供字符串中最后一個點字符的位置,然后您可以使用它來相應地拆分字符串。

rfind + substr一樣簡單

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

利用函數std :: find_last_of然后使用string :: substr來實現所需的結果。

搜索第一個'。' 從右邊開始。 使用substr提取子字符串。

另一種可能的解決方案,假設您可以更新原始字符串。

  1. 取char指針,從最后遍歷。

  2. 第一次停止'。' 找到后,將其替換為'\\ 0'null字符。

  3. 將char指針指定給該位置。

現在你有兩個字符串。

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

我沒有包括測試用例,如果'。' 最后,或任何其他。

如果你想使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM