在另一个字符串中查找字符串的位置

bit*_*ion 2 c++ string algorithm query-string data-structures

可能重复:
子串算法

给定两个字符串A和B,如何在A中找到B的第一个位置?例如,A ="ab123cdefgcde"; B ="cde"然后A中B的第一个位置是5.

有什么技巧可以解决这个问题,或者只是从头开始搜索A?

osg*_*sgx 6

你真的必须从头开始扫描A.

有很好的快速子串搜索算法,例如http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm

还有一个标准功能strstr:

strstr(A,B)
Run Code Online (Sandbox Code Playgroud)

http://www.cplusplus.com/reference/clibrary/cstring/strstr/

  • 或者在C++的情况下`std :: string :: find`. (4认同)