5

I wanna know if there is any standard function in visual stodio 2010, C++, which takes a character, and returns the index of it in special string, if it is exist in the string. Tnx

rain
  • 383
  • 2
  • 5
  • 14

4 Answers4

5

You can use std::strchr.

If you have a C like string:

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

If you have a std::string instance:

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

With a std::string you can also a method on it to find the character you are looking for.

Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
  • Sorry, the problem was with my test file, I used find method. 'MyIndex= MyString.find('.');' Tnx – rain Dec 07 '10 at 12:40
3

strchr or std::string::find, depending on the type of string?

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • @rain: `std::wstring` and `std::string` are just specializations of `std::basic_string<>`, they offer the very same methods... – Matthieu M. Dec 07 '10 at 13:09
2

strchr() returns a pointer to the character in the string.

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 
DanS
  • 1,677
  • 20
  • 30
1
#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;
}
MSalters
  • 173,980
  • 10
  • 155
  • 350
João Víctor
  • 1,731
  • 1
  • 9
  • 4
  • `foo.cpp:13:12: warning: comparison of integer expressions of different signedness`. Maybe use `size_t idx` and see also [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – ggorlen Mar 11 '22 at 17:22