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

33

例如,如果我有

string x = "dog:cat";

我想提取冒号后面的所有内容,并返回cat。怎么做呢?


1
请看这里的示例:http://www.cplusplus.com/reference/string/string/substr/ - Dronz
这个问题如果进行了一点研究就可以避免。 - sjsam
9
也许是这样,但它现在是谷歌搜索结果的首选。 - Ben Fulton
9个回答

86

试试这个:

x.substr(x.find(":") + 1); 

这太棒了!!<3 - Spandyie
1
这会创建一个副本,这可能不是你想要的。在C++17中,您可以使用std::string_view来避免复制。 - Kyle
2
正如其他答案中提到的那样,您应该处理 find 返回 npos 的边缘情况。并不保证 npos + 1 等于 0(请参见 https://dev59.com/v4Tba4cB1Zd3GeqP4VP5)。 - galsh83
2
如果我有 "cat:dog:parrot:horse",并且我只想得到 horse,该怎么办?(也就是最后一个 :)) - User123
@rcs 我应该如何在C编程中完全做相同的事情? - Virtuall.Kingg

15

我知道已经很晚了,但我无法评论被接受的答案。如果您在find函数中仅使用单个字符,请改用''而不是""。 正如Clang-Tidy所说:字符字面量重载更高效。

因此     x.substr(x.find(':') + 1)


11

来自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;

很多程序员由于没有执行适当的错误检查而犯错。该字符串具有操作者感兴趣的哨兵,但如果pos > size(),则会抛出std::out_of_range异常。

basic_string substr( size_type pos = 0, size_type count = npos ) const;

5
#include <iostream>
#include <string>

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

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

这里是一个包装在函数中的实现,可以适用于任意长度的分隔符:
#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';

}

考虑到任意长度的分隔符是非常聪明的,所以加一。 - sjsam

2

类似于这样的内容:

string x = "dog:cat";
int i = x.find_first_of(":");
string cat = x.substr(i+1);

1

Try this:

  string x="dog:cat";
  int pos = x.find(":");
  string sub = x.substr (pos+1);
  cout << sub;

1
#include <string>
#include <iostream>
std::string process(std::string const& s)
{
    std::string::size_type pos = s.find(':');
    if (pos!= std::string::npos)
    {
        return s.substr(pos+1,s.length());
    }
    else
    {
        return s;
    }
}
int main()
{
    std::string s = process("dog:cat");
    std::cout << s;
}

我已经执行了这段代码,它可以运行。http://www.tutorialspoint.com/compile_cpp_online.php - Brahmanand Choudhary

1
你可以获取字符串中 ':' 的位置,然后使用 substring 获取该位置之后的所有内容。 size_t pos = x.find(":"); // 在字符串中找到 ":" 的位置 string str3 = str.substr (pos);

0

试试这个..

std::stringstream x("dog:cat");
std::string segment;
std::vector<std::string> seglist;

while(std::getline(x, segment, ':'))
{
   seglist.push_back(segment);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接