boom
boom

Reputation: 6166

searching a character in a string

How can i search a character " in a string.

Upvotes: 0

Views: 5626

Answers (5)

msemelman
msemelman

Reputation: 2937

You can use string::find() function. visit here for more info

#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); 
}

it's very important to escape the " character inside defined strings.

Upvotes: 3

Zai
Zai

Reputation: 1175

This is the solution that doesn't have any depedency with library in C++

char * foo = "abcdefg";

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

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

Upvotes: 0

faya
faya

Reputation: 5715

Here is simple solution:

#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);
}

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

string::find()

Upvotes: 2

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95489

The best you can do for finding a character in an unsorted string is a linear search:

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

There is, of course, a function for doing that already: std::string::find, which will return std::string::npos if the character is not found; otherwise, the function will return the index at which the character is first found. There are also variations of find like std::string::find_first_of, std::string::find_last_of, and their "not_of" variants.

Upvotes: 2

Related Questions