Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如果字符串的第一部分匹配(从头开始),删除它的最简单方法是什么?(使用boost就可以了)_C++_Boost_Algorithm_C++17 - Fatal编程技术网

C++ 如果字符串的第一部分匹配(从头开始),删除它的最简单方法是什么?(使用boost就可以了)

C++ 如果字符串的第一部分匹配(从头开始),删除它的最简单方法是什么?(使用boost就可以了),c++,boost,algorithm,c++17,C++,Boost,Algorithm,C++17,若字符串从一开始就匹配,那个么将其删除或以一个新字符串的形式返回,并没有关系。结果应该是世界 最愚蠢最简单的方法是什么?最好使用一个衬里。性能不是一个问题。std是首选,但也是一个选项。可能不是最佳性能,但有一行: std::string str_a = "Hello World"; std::string str_b = "Hello "; #include <iostream> #include <string> int m

若字符串从一开始就匹配,那个么将其删除或以一个新字符串的形式返回,并没有关系。结果应该是世界


最愚蠢最简单的方法是什么?最好使用一个衬里。性能不是一个问题。std是首选,但也是一个选项。

可能不是最佳性能,但有一行:

std::string str_a = "Hello World";
std::string str_b = "Hello ";
#include <iostream>
#include <string>

int main()
{
   std::string a = "Hello World";
   std::string b = "Hello ";

   if (a.find(b) == 0)
   {
       std::cout << "\"" << a.substr(b.length()) << "\"\n";
   }

   return 0;
}

似乎简单有效。

如果性能不是一个问题,这是一个很好的答案。但这不是我自己会做的,因为find将搜索源字符串中的所有位置,直到找到匹配项,而不仅仅是第一个。同意,尽管它明确指出;-但是,如果他能够升级到C++20,他可以使用std::string::starts_,这应该会提供更好的性能。@CornhioBoost已经开始使用了,我可以使用它,如果你已经使用boost,那么就这样做,尽管我不会为这样的任务引入boost依赖项。查看@John的答案,这是一种比我的基于查找的解决方案更好的检查字符串是否以另一个字符串开头的方法-@Cornholio我认为这个使用find的方法更清晰,性能也无关紧要,但使用start\u时更清晰
std::string str_c = (str_a.find(str_b) == 0) ? str_a.substr(str_b.size()) : str_a;
if (str_a.compare(0, str_b.size(), str_b) == 0)
    str_a = str_a.substr(str_b.size());