2010-05-09 189 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