2010-12-07 5 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 ('. ');' Txx – 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; 
}