Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the index of a special character in string in C++

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

like image 882
rain Avatar asked Dec 07 '10 12:12

rain


People also ask

How do you find the index of a special character in a string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do you find the index of a specific character?

To get the index of a character in a string, you use the indexOf() method, passing it the specific character as a parameter. This method returns the index of the first occurrence of the character or -1 if the character is not found.

Can you index a string in c?

The index() function locates the first occurrence of c (converted to an unsigned char) in the string pointed to by string. The character c can be the NULL character (\0); the ending NULL is included in the search. The string argument to the function must contain a NULL character (\0) marking the end of the string.

How do you find the index of a specific character in a string in C++?

string::find() function returns the index of first occurrence of given substring in this string, if there is an occurrence of substring in this string. If the given substring is not present in this string, find() returns -1.


2 Answers

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.

like image 110
Pablo Santa Cruz Avatar answered Oct 19 '22 23:10

Pablo Santa Cruz


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

like image 29
NPE Avatar answered Oct 19 '22 23:10

NPE