2010-05-09 188 views
0

如何在字符串中搜索字符"搜索字符串中的字符

+0

你期待在那个角色中找到什么?还总是记得第四次修正案。 :-) – Thomas 2010-05-09 07:23:17

+0

你的意思是'\“'字符吗? – qba 2010-05-09 18:11:42

回答

2

您可以在未排序的字符串查找的字符做的最好的是线性搜索:

for each index in the string: 
     if the character at that index matches the search criteria: 
       report the current index 
report not found 

有,当然,做这件事已经是一个功能:std::string::find,这将返回std::string::npos如果字符未找到;否则,该函数将返回首次找到该字符的索引。还有像std::string::find_first_of,std::string::find_last_of这样的查找变体,以及它们的“not_of”变体。

3

您可以使用string :: find()函数。参观here更多信息

#include <string> 
using namespace std; 

int main() 
{ 
    string str ("foo\"bar"); 
    string str2 ("\""); 
    size_t found; 
    //you may want to do str.find('"') if you are only looking for one char. 
    found=str.find(str2); 
} 

它逃跑定义字符串里面的“字符是非常重要的

+0

或者不用分配一个新的字符串来保存''\”“'''''''''''' – 2010-05-09 13:28:07

+0

@wintermute谢谢你 – msemelman 2010-05-09 18:01:32

2

下面是简单的解决方案:

#include <string.h> 

using namespace std; 

int findChar(char c, string myString) 
{ 
    pos = myString.find(c); // Find position in the string (to access myString[pos]) 
    return int(pos); 
} 
0

这是没有解决任何依赖与C++中的库

char * foo = "abcdefg"; 

char cf = 'e'; // Char to find 

int f = 0; while (*(foo + f++) != cf); // f is 5