C++如何获得字符后的子字符串?

SKL*_*LAK 18 c++ string substring

例如,如果我有

string x = "dog:cat";
Run Code Online (Sandbox Code Playgroud)

我想在":"之后提取所有内容,并返回cat.这样做的方法是什么?

rcs*_*rcs 60

试试这个:

x.substr(x.find(":") + 1); 
Run Code Online (Sandbox Code Playgroud)

  • 正如其他一些答案中提到的,您应该处理“find”返回“npos”的边缘情况。不保证“npos + 1”等于 0(请参阅 /sf/ask/1848207301/)。 (2认同)
  • 如果我有“cat:dog:parrot:horse”并且我只想得到马怎么办?(所以最后一张:) (2认同)

New*_*bie 11

我知道这会很晚,但我无法评论已接受的答案。如果您仅使用单个字符find函数使用''代替""。正如 Clang-Tidy 所说The character literal overload is more efficient.

所以 x.substr(x.find(':') + 1)


小智 7

来自rcs的公认答案可以改进。没有代表,所以我无法对答案发表评论。

std::string x = "dog:cat";
std::string substr;
auto npos = x.find(":");

if (npos != std::string::npos)
    substr = x.substr(npos + 1);

if (!substr.empty())
    ; // Found substring;
Run Code Online (Sandbox Code Playgroud)

不执行正确的错误检查会绊倒很多程序员。该字符串具有 OP 感兴趣的标记,但如果 pos > size() 则抛出 std::out_of_range。

basic_string substr( size_type pos = 0, size_type count = npos ) const;
Run Code Online (Sandbox Code Playgroud)


Tre*_*key 5

#include <iostream>
#include <string>

int main(){
  std::string x = "dog:cat";

  //prints cat
  std::cout << x.substr(x.find(":") + 1) << '\n';
}
Run Code Online (Sandbox Code Playgroud)

下面是一个封装在函数中的实现,该函数可以处理任意长度的分隔符:

#include <iostream>
#include <string>

std::string get_right_of_delim(std::string const& str, std::string const& delim){
  return str.substr(str.find(delim) + delim.size());
}

int main(){

  //prints cat
  std::cout << get_right_of_delim("dog::cat","::") << '\n';

}
Run Code Online (Sandbox Code Playgroud)