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

5 Answers. Just subtract the string address from what strchr returns: char *string = “qwerty”; char *e; int index; e = strchr(string, ‘e’); index = (int)(e – string); Note that the result is zero based, so in above example it will be 2.Click to see full answer. Also to know is, how do you find the index of a character in a string C++? Solution: Read a string str and character ch whose last index to be found. Get the length of the string (length). Run loop from length-1 to 0. Check character with each character of the string, if it is found return the index (loop counter’s value) (which will be the result). Secondly, how do I find a character in a string? To locate a character in a string, use the indexOf() method. Let’s say the following is our string. String str = “testdemo”; Find a character ‘d’ in a string and get the index. Correspondingly, how do you check if a character is in a string C? char *strchr(const char *s, int c); The strchr function locates the first occurrence of c (converted to a char ) in the string pointed to by s . The strchr function returns a pointer to the located character, or a null pointer if the character does not occur in the string.What function can return the index of a character in a string?The INDEXOF function allows for two string values to be used and returns the index of the second value within the first value. If “example” is the first value and we’re looking for ‘x’ within it, the expression would return 1.

Leave a Reply

Your email address will not be published. Required fields are marked *