2010-12-07 20 views

答えて

4

std::strchrを使用できます。

あなたは文字列のようなC持ちの場合:あなたはstd::stringインスタンスがある場合は

const char *s = "hello, weird + char."; 
strchr(s, '+'); // will return 13, which is '+' position within string 

を:std::string

std::string s = "hello, weird + char."; 
strchr(s.c_str(), '+'); // 13! 

をあなたもそれにメソッドが文字を見つけることができます探しています。

+0

これはstd :: wstring、手伝ってくれませんか? – rain

+0

申し訳ありませんが、問題は私のテストファイルで、私はfindメソッドを使用しました。 'MyIndex = MyString.find('。 ');' Tnx – rain

3

strchrまたはstd::string::find(文字列の種類によって異なりますか?

+0

私はむしろはstd :: wstringの思いを。 – rain

+0

@rain: 'std :: wstring'と' std :: string'は 'std :: basic_string <>'の特殊化であり、非常に同じメソッドを提供しています... –

2

strchr()は、文字列内の文字へのポインタを返します。

const char *s = "hello, weird + char."; 
char *pc = strchr(s, '+'); // returns a pointer to '+' in the string 
int idx = pc - s; // idx 13, which is '+' position within string 
0
#include <iostream> 
#include <string> 
#include <algorithm> 

using namespace std; 

int main() { 
    string text = "this is a sample string"; 
    string target = "sample"; 

    int idx = text.find(target); 

    if (idx!=string::npos) { 
     cout << "find at index: " << idx << endl; 
    } else { 
     cout << "not found" << endl; 
    } 

    return 0; 
} 
関連する問題